Search code examples
svgpolygonbezier

Turn SVG Into Sequence Of Points


Given an SVG, is there a library which helps me to turn any path of the file into a sequence of points which lie on the path, with the length of path between two consecutive points being 1 (or some other constant)?


Solution

  • There is no need for a library. The SVGGeometryElement API makes this possible within a few lines of code:

    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>