如何获得< g>的中点在使用JavaScript的svg中标记 [英] How to get Mid point of <g> tag in svg using javascript

查看:91
本文介绍了如何获得< g>的中点在使用JavaScript的svg中标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaScript工作在SVG标记中。我试图在svg中获取组标记< g> 中点。是否有可能使用JavaScript获得组标记的中点值?
这是我的演示组标记< g>

I am working in SVG tags using javascript. I tried to get group tag <g> midpoint in svg. Is it possible to get mid point value of group tag using javascript? Here's my demo group tag <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位置的中心位置,但我没有实现它。任何人都可以引导我吗?

Here I need to get midpoint point of group tag. I used to get mouse co-ordinates for getting center of x and y position in group tag, but I did not achieve it. Can anyone please guide me?

推荐答案

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

You can get the bounding box of the <g> element by getting a reference to it and calling the function getBBox().

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

请注意,这是组的所有边界框的联合。如果该组具有变换,则不会反映在bbox值中。如果您要添加元素到组中,这可能是您想要的元素。

Note however that this is the union of all the bounding boxes of the group's children. If the group has a transform, it is not reflected in the bbox value. If you are adding elements to the group, this is probably the one you want.

如果您希望屏幕空间中的对象边界,那么您可以获得组

If you want the bounds of the object in screen space, then you can get the group element's transform and apply it to the centre point you have calculated.

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

此处演示

这篇关于如何获得&lt; g&gt;的中点在使用JavaScript的svg中标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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