如何获取已分组的svg元素的全局坐标? [英] How do I get the global coordinates of a grouped svg element?

查看:234
本文介绍了如何获取已分组的svg元素的全局坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下文档(小提琴):

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

假设我不知道它在一个组中,如何获取rect元素的全局坐标?

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

推荐答案

实际上很难找到.搜索SVGElement的方法将导致页面显示SVGElement没有方法!实际上,它确实有很多方法,但是它们是继承的:

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

根据需要,可以使用getCTMgetScreenCTM的结果来转换SVGPoint,从而了解元素的位置:

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/

这篇关于如何获取已分组的svg元素的全局坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆