Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the global coordinates of a grouped svg element?

Suppose I have the following document (fiddle):

<svg>
    <g transform="translate(50,50)">
        <rect width="20" height="20" style="fill:black;">
    </g>
</svg>

How do I get the global coordinates of the rect element assuming I don't know that it's in a group?

like image 581
Dane O'Connor Avatar asked Jul 23 '13 18:07

Dane O'Connor


People also ask

What is the g in SVG?

The SVG <g> element is a container used to group other SVG elements. Transformations applied to the <g> element are also performed on its child elements, and its attributes are inherited by its children.


1 Answers

It was actually kind of hard to find. Searching for methods of SVGElement results in pages saying SVGElement has no methods! It does in fact have a ton of methods, but they are inherited:

http://www.w3.org/TR/SVG/types.html#InterfaceSVGLocatable

Depending on what you want you can use the result of getCTM or getScreenCTM to transform a SVGPoint, and thus learn where you element is:

root = document.getElementById('root')
rec = document.getElementById('rec')
point = root.createSVGPoint()
# This is the top-left relative to the SVG element
ctm = rec.getCTM()
console.log point.matrixTransform(ctm)
# This is the top-left relative to the document
ctm = rec.getScreenCTM()
console.log point.matrixTransform(ctm)

http://jsfiddle.net/kitsu_eb/ZXVAX/3/

like image 121
kitsu.eb Avatar answered Nov 15 '22 06:11

kitsu.eb