查找SVG的中心点坐标

时间:2019-06-09 04:40:40

标签: javascript html css svg

我正在寻找一种可以通过路径找到SVG线中心的解决方案,因为我想将异物渲染到SVG中心。

这是我的代码

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <svg>
    <g
      stroke-linecap="round"
      data-linkid="36141ffc-14b0-4375-9d40-8d002ac597fc"
      stroke-opacity="0"
      stroke-width="20"
      ><svg>
        <path
          stroke-width="10"
          stroke="rgba(255,0,0,0.5)"
          d="M68.6875,52.6875 C 68.6875,102.6875
    379.6875,331.6875 379.6875,381.6875"
          tets="Fd"
        ></path>
        <foreignObject x="50" y="50" height="100" width="40">
          <div xmlns="http://www.w3.org/1999/xhtml">
            <h1>HI</h1>
          </div>
        </foreignObject>
      </svg></g
    >
    </svg>
    <script src="src/index.js"></script>
  </body>
</html>

如您在上面的用于渲染异物的代码中所见,我已将静态x和y坐标传递为50。如何计算中心点,以使HI精确地位于我的SVG的中心?

1 个答案:

答案 0 :(得分:0)

我做了一些搜索,发现了这个 stack overflow answer

基本上,您要做的是使用返回矩形元素的getBBoxgetBoundingClientRect命令找到可以放在svg元素周围的最小矩形。然后,您可以获取该元素的宽度和高度,并将这两个字段都除以二,以获得该rect元素的中心。

mySVG = someRandomSVGElement;
surroundingRectangle = mySVG.getBoundingClientRect();

centerOfRect_X = surroundingRectangle.width/2;
centerOfRect_Y = surroundingRectangle.height/2;

然后将其添加到rect元素的x和y中,以获取mySVG元素中心的坐标。

centerOfmySVG_X = centerOfRect_X + surroundingRectangle.x;
centerOfmySCG_Y = centerOfRect_Y + surroundingRectangle.y;
相关问题