gpt4 book ai didi

javascript - 如何使用javascript获取svg中标签的中点

转载 作者:太空宇宙 更新时间:2023-11-04 14:15:50 26 4
gpt4 key购买 nike

我正在使用 JavaScript 处理 SVG 标签。我试图获取组标签 <g> svg 中的中点。是否可以使用 javascript 获取组标签的中点值?这是我的演示组标签 <g>

<g id="object_7" transform="translate(573,703) scale(0.5,0.51)" style="pointer-events:inherit">

<path d="m-40,-19l3,-3l74,0l3,3l0,37l-3,3l-74,0l-3,-3l0,-37z" id="uid127" stroke-linejoin="round" stroke-linecap="round" fill="#1e1d19" stroke="#000000"/>

<path d="m-9,21l4,2l10,0l4,-2" id="uid129" stroke-linejoin="round" stroke-linecap="round" fill-opacity="0" fill="none" stroke="#000"/>

<path d="m-40,-19l3,-3l74,0l3,3l-77,40l-3,-3l0,-37z" id="uid131" stroke-linejoin="round" stroke-linecap="round" fill-opacity="0.12" fill="#000000"/>

</g>

这里我需要获取组标签的中点。我曾经通过获取鼠标坐标来获取组标签中 x 和 y 位置的中心,但我没有实现。谁能指导我?

最佳答案

可以得到<g>的边界框通过获取对元素的引用并调用函数 getBBox() 来获取元素.

var  bbox = document.getElementById("object_7").getBBox();

但是请注意,这是该组子项的所有边界框的并集​​。如果该组有变换,则不会反射(reflect)在 bbox 值中。如果您要向组中添加元素,这可能就是您想要的。

如果您想要屏幕空间中对象的边界,那么您可以获得组元素的变换并将其应用于您计算出的中心点。

var  ctm = document.getElementById("object_7").getCTM()

// Calculate the centre of the group
var cx = bbox.x + bbox.width/2;
var cy = bbox.y + bbox.height/2;

// Transform cx,cy by the group's transform
var pt = document.getElementById("mysvg").createSVGPoint();
pt.x = cx;
pt.y = cy;
pt = pt.matrixTransform(ctm);

// centre point in screen coordinates is in pt.x and pt.y

Demo here

关于javascript - 如何使用javascript获取svg中<g>标签的中点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26867641/

26 4 0