Alexander Solonik Alexander Solonik - 3 months ago 12
Javascript Question

What is g() in snap SVG

Hey guys i was going through THIS snap.svg demo, Now when i check the code on my local machine , it looks like below:

var g = Snap();
g.attr({
viewBox: [0, 0, 800, 600]
});

Snap.load("map.svg", function (f) {
function getShift(dot) {
return "t" + (400 - dot.x) + "," + (300 - dot.y);
}
var gr = f.select("g"),
wrd = f.select("#world").attr({fill: "#fff"}),
syd = f.select("#sydney").attr({fill: "red"}),
msk = f.select("#san_francisco").attr({fill: "red"}),
pth = f.select("#flight"),
pln = f.select("#plane"),
top = g.g();
top.attr({
mask: g.rect(100, 0, 600, 600).attr({
fill: "r(.5,.5,.25)#fff-#000"
})
});


I am just posting the initial part of the code that i am struggling to understand , in the above portion of the code there is the below line:

top = g.g();


Now of course looking at the snippet you can see that
g
is an instance of
snap()
but why the above line of code ?? The SVG i am dealing with is THIS.

I am not quite understanding the line of code
g.g()
. Can anybody explain ?

Ian Ian
Answer

Oddly their code is slightly confusing. First of all I would not do this, I'm a little surprised...

var g = Snap();

g normally means 'group'. However, Snap() does NOT return a group, it returns a Snap 'svg' element.

So instead I think they would normally do the following now which reads better...

var s = Snap()   // its an svg or snap instance 

or

var paper = Snap() // its typically known as a paper you draw on

So then it would lead to this line instead, which 'looks' more correct when reading...

var top = paper.group() // you can use g and group interchangeably.

Which means add a 'group' container to the paper/svg element.

Comments