Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get g bounding box in svg units

Tags:

javascript

svg

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?

like image 898
abergmeier Avatar asked Jan 18 '26 06:01

abergmeier


1 Answers

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);
like image 64
Richard M Avatar answered Jan 21 '26 09:01

Richard M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!