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

天涯浪子 提交于 2019-12-18 16:09:06

问题


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?


回答1:


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/




回答2:


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



来源:https://stackoverflow.com/questions/17817790/how-do-i-get-the-global-coordinates-of-a-grouped-svg-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!