SVG:获取弧段长度



我正在研究在Node.js中计算path.getTotalLength()的方法,但似乎没有polyfill。到目前为止,我设法计算了除A之外的所有其他pathCommands。

例如,知道M段的最后一个X和Y,以及所有A段的值,如何确定该路径的长度?

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">
<path d="M8 15 A7 7 0 1 0 8 1">
</svg>

谢谢

MDN有一些关于各种路径命令的优秀文档。

MDN>SVG教程>路径

以下是如何分解提供的路径命令:

M 8 15=移动到(绝对(

x = 8
y = 15

A 7 7 0 1 0 8 1=电弧(绝对(

rx = 7
ry = 7
x-axis-rotation = 0
large-arc-flag = 1
sweep-flag = 0
x = 8
y = 1

我遵循了这篇数学交流文章,在给定状态路径命令的情况下计算弧长。由于圆弧的x和y半径相等,所以这会容易一些。

注意:如果它们不同,我不确定您需要做什么。

const x1 = 8, y1 = 15;
const x2 = 8, y2 =  1;
const r  = 7; // Since rx === ry, this is a bit easier
const d = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
const theta = Math.acos(1 - (Math.pow(d, 2) / (2 * Math.pow(r, 2))));
const arcLength = theta * r;
console.log(arcLength); // Arc Length = 21.9911
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">
<path d="
M 8 15
A 7 7 0 1 0 8 1
" fill="none" stroke="black" stroke-width="2" />
<!-- Move to and begin arc at (8, 15) -->
<circle cx="8" cy="15" r="1" stroke="none" fill="red" />

<!-- End arc at (8, 1) -->
<circle cx="8" cy="1" r="1" stroke="none" fill="cyan" />

<!-- Radius of (7, 7) -->
<circle cx="15" cy="7.5" r="1" stroke="none" fill="lime" />

<!-- Center -->
<circle cx="8" cy="7.5" r="1" stroke="none" fill="gold" />
</svg>

最新更新