将SVG转换成点序列

问题描述

给定一个SVG,是否有一个库可以帮助我将文件的任何路径转换为位于路径上的点序列,两个连续点之间的路径长度为1(或某个其他常数)?

解决方法

不需要图书馆。 SVGGeometryElement API通过几行代码即可实现这一点:

function getPointsAlongPath (path,distance) {
  const length = path.getTotalLength();
  const points = [];

  for (let step = 0; step <= length; step = step + distance) {
    points.push(path.getPointAtLength(step));
  }
  
  return points;
}

const result = getPointsAlongPath(document.querySelector('circle'),5);
console.log(result.map(p => [p.x,p.y]));
<svg width="100" viewBox="0 0 100 100">
  <circle cx="50" cy="50" r="40" fill="none" stroke="black" />
</svg>