Reputation: 14071
I am trying to implement a menu in Javascript with single menu-items being svg:g
.
To mark an item as selected I would like to move another svg:g
on top of the menu-item.
For this I need to get the bounding box of the menu-item (=svg:g
) so I can apply the rect (x, y, width, height) to the other. I have not found a convenient way yet, for getting the bounding box of a svg:g
.
The only way I can think of would be recursing into the children and calculating the bounding box (approximation) by hand. Is there a more elegant way?
Upvotes: 3
Views: 6737
Reputation: 14543
You should just be able to use the getBBox
method of your group element.
e.g. http://jsfiddle.net/PFnre/1/
var root = document.createElementNS("http://www.w3.org/2000/svg", "svg");
document.body.appendChild(root);
var g = document.createElementNS("http://www.w3.org/2000/svg", "g");
root.appendChild(g);
var r = document.createElementNS("http://www.w3.org/2000/svg", "rect");
r.setAttribute("x", "50");
r.setAttribute("y", "60");
r.setAttribute("width", "100");
r.setAttribute("height", "110");
r.setAttribute("fill", "blue");
g.appendChild(r);
var c = document.createElementNS("http://www.w3.org/2000/svg", "circle");
c.setAttribute("cx", "150");
c.setAttribute("cy", "140");
c.setAttribute("r", "60");
c.setAttribute("fill", "red");
g.appendChild(c);
var bbox = g.getBBox();
var o = document.createElementNS("http://www.w3.org/2000/svg", "rect");
o.setAttribute("x", bbox.x);
o.setAttribute("y", bbox.y);
o.setAttribute("width", bbox.width);
o.setAttribute("height", bbox.height);
o.setAttribute("stroke", 'black')
o.setAttribute("fill", 'none');
root.appendChild(o);
Upvotes: 3