最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I get the global coordinates of a grouped svg element? - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Jul 23, 2013 at 18:08 Dane O'ConnorDane O'Connor 77.3k39 gold badges120 silver badges174 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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/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/kitsu_eb/ZXVAX/3/

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/es/docs/Web/API/Element/getBoundingClientRect

发布评论

评论列表(0)

  1. 暂无评论