我正在寻找一种可以通过路径找到 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 的中心?
最佳答案
我做了一些搜索,找到了这个 stack overflow answer
基本上,您要做的是使用 getBBox 找到可以适合 svg 元素的最小矩形。或 getBoundingClientRect命令返回一个矩形元素。然后,您可以获得该元素的宽度和高度,并将这两个字段除以二以获得该矩形元素的中心。
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;
附录(2020 年 11 月):使用 ES 解构:
let { x, y, width, height } = svgElement.getBoundingClientRect();
let cx = width / 2 + x;
let cy = height / 2 + y;
关于javascript - 寻找SVG的中心点坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56512018/