<...">

How to get 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 to get the global coordinates of a rect element, provided that I do not know what it is in the group?

+7
javascript svg coordinates
source share
2 answers

It was actually hard to find. Searching for SVGElement methods SVGElement that pages containing SVGElement have no methods! He actually has a ton of methods, but they inherit:

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

Depending on what you want, you can use the result of getCTM or getScreenCTM to convert a SVGPoint and thus find out where your 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/

+13
source share

You can use the .getBoundingClientRect() function to get the bounding box. Then use the values ​​of height , width , top and left to find the center position of your element.

Refer to https://developer.mozilla.org/es/docs/Web/API/Element/getBoundingClientRect

0
source share

All Articles