SVG:获取弧段长度

时间:2020-09-14 18:37:33

标签: javascript 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>

谢谢

1 个答案:

答案 0 :(得分:1)

MDN关于各种路径命令都有一些很棒的文档。

MDN > SVG Tutorial > Paths

以下是分解提供的路径命令的方式:

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

在给出状态路径命令的情况下,我遵循此Mathematics Exchange post来计算弧长。由于圆弧的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>

相关问题