【问题标题】:How to get Mid point of <g> tag in svg using javascript如何使用javascript在svg中获取<g>标签的中点
【发布时间】:2014-11-11 14:51:34
【问题描述】:

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

<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 位置的中心,但我没有实现。谁能指导一下?

【问题讨论】:

    标签: javascript html svg


    【解决方案1】:

    您可以通过获取&lt;g&gt; 元素的引用并调用函数getBBox() 来获取它的边界框。

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

    但请注意,这是该组子项的所有边界框的并集​​。如果组有变换,则不会反映在 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

    【讨论】:

    • 它的结果只有屏幕中心值,但我需要获取对象中点值?如何度过难关?可以请指导我..
    • 我不明白。 “对象中点值”是什么意思?你不想要“物体中心”吗?
    • 是的,我想要组对象的中心。但是,在您的代码结果中,只有工作区屏幕中心。我想拖动 svg 对象并放置在工作区中。我需要获取单个 svg 对象中心..
    • 我不确定您所说的“工作区屏幕中心”是什么意思。如果您想要任何元素的中心在本地坐标中,请在其上调用 getBBox() 并使用上面的 cx,cy 计算。
    【解决方案2】:

    如果你想得到屏幕中g标签的绝对中点/位置:

    let el = document.getElementById("object_7")
    let midX = (el.getBoundingClientRect().left + el.getBoundingClientRect().right) / 2
    let midY = (el.getBoundingClientRect().top + el.getBoundingClientRect().bottom) / 2
    

    它也适用于其他 svg 元素。

    【讨论】:

      猜你喜欢
      • 2014-09-08
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-07
      • 2023-03-10
      • 2021-08-19
      • 2013-06-07
      相关资源
      最近更新 更多