javascript - 如何获取分组 svg 元素的全局坐标?

标签 javascript svg coordinates

假设我有以下 document (fiddle) :

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

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

最佳答案

其实有点难找。搜索 SVGElement 的方法会导致页面显示 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/

关于javascript - 如何获取分组 svg 元素的全局坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17817790/

相关文章:

javascript - SVG : how to properly handle mouseover and mouseout event?

opengl - Wavefront *.OBJ 文件中的第三个纹理坐标

mysql - 计算 400 个城市之间的距离并为此优化 MySQL?

CSS SVG 将垂直中间与标签对齐

css - 如何制作动画、渐变填充的 SVG 圆环图

c# - 如何找到黑色像素位置

javascript - Z 索引未正确显示

javascript - 在滚动条上显示一系列图像

javascript - 延迟函数运行 n 秒,然后运行一次。 (2分钟问题)

javascript - 使用 jquery 的下拉导航链接未在 mvc 中加载有效的 anchor 链接