9

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?

Dane O'Connor
  • 75,180
  • 37
  • 119
  • 173

2 Answers2

14

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/

kitsu.eb
  • 2,996
  • 1
  • 26
  • 28
  • Nice! I didn't know about matrixTransform. The javascript is empty in your fiddle. Did you update? Trying to test this out. – Dane O'Connor Jul 23 '13 at 19:52
  • I tried thedeeno's linked fiddle, but I didn't get the result I expected. Here is a fork that uses getBBox to set the point's initial coords: http://jsfiddle.net/kitsu_eb/T8aZP/15/ – kitsu.eb Jul 23 '13 at 22:16
  • Apparently SVGMatrix is deprecated: https://developer.mozilla.org/en/docs/Web/API/SVGMatrix Doesn't that make getScreenCTM and getCTM deprecated as well? – Jaakko Karhu Feb 09 '17 at 12:20
0

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

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

Styx
  • 9,863
  • 8
  • 43
  • 53