如何获取分组的SVG元素的全局坐标?

9
假设我有以下的文档(fiddle):链接
<svg>
    <g transform="translate(50,50)">
        <rect width="20" height="20" style="fill:black;">
    </g>
</svg>

如果不知道矩形元素在组中,如何获取该元素的全局坐标?
2个回答

14

实际上,找到相关方法有点难。搜索 SVGElement 的方法会出现页面显示该元素没有方法!但它实际上有大量的方法,只是这些方法被继承了:

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

根据你需要的功能,你可以使用 getCTMgetScreenCTM 的结果来转换一个 SVGPoint,从而确定元素的位置:

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/


太好了!我不知道 matrixTransform 这个函数。你在你的 fiddle 代码编辑器里的 Javascript 是空的,你更新了它吗?我正在尝试测试这个功能。 - Dane O'Connor
我尝试了thedeeno的链接fiddle,但是我没有得到我期望的结果。这里是一个fork,它使用getBBox来设置点的初始坐标:http://jsfiddle.net/kitsu_eb/T8aZP/15/。 - kitsu.eb
显然SVGMatrix已经被弃用:https://developer.mozilla.org/en/docs/Web/API/SVGMatrix这是否也意味着getScreenCTM和getCTM也被弃用了? - Jaakko Karhu

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接