简体   繁体   中英

SVG: get arc segment length

I'm looking into ways to calculate path.getTotalLength() in Node.js and it seems that a polyfill is not available. So far I managed to compute all other pathCommands except A .

For instance, knowing last X and Y from M segment, and also having all the A segment values, how to determine the length of this path?

<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>

Thank you

MDN has some great documentation in regards to the various path commands.

MDN > SVG Tutorial > Paths

Here is how you decompose the provided path commands:

M 8 15 = Move To (Absolute)

x = 8
y = 15

A 7 7 0 1 0 8 1 = Arc (Absolute)

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

I followed this Mathematics Exchange post to compute the arc length, given the states path commands. Since the x and y radii of your arc are equal, this is a bit easier.

Note: I am not sure what you would need to do if they are different.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM