How to get group element render position?

925 views Asked by At

Refer to the code below, the position of the bounding box is not the actual render position of the group of the elements.

The group element can be used to construct a very complicated unit like a Tank / Ship with cannons. And group element doesn't have X or Y property to help move the inner elements so I have to use the transform to move the Tank / Ship.

However, I realized that when I translate the group, the bounding box never reflect the real render position any more, does any one have any idea how to get the actual render position of the group?

http://jsfiddle.net/k4uhwLj4/

var root = document.createElementNS("http://www.w3.org/2000/svg", "svg");
root.style.width = '500px';
root.style.height = '500px';
document.body.appendChild(root);

var g = document.createElementNS("http://www.w3.org/2000/svg", "g");
g.setAttributeNS(null, 'transform', 'translate(50, 50)');
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");
r.setAttributeNS(null, 'transform', 'translate(50, 50)');
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);
1

There are 1 answers

0
methodofaction On BEST ANSWER

The .getBBox() method doesn't take transformation into account (per spec) according to this post:

How is the getBBox() SVGRect calculated?

To solve this you can add a parent g that has no transform attribute:

var parentG = document.createElementNS("http://www.w3.org/2000/svg", "g");
root.appendChild(parentG);

var g = document.createElementNS("http://www.w3.org/2000/svg", "g");
g.setAttributeNS(null, 'transform', 'translate(50, 50)');
parentG.appendChild(g);

http://jsfiddle.net/sydgc091/