Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert SVG path to polygon coordinates

I need a function or plugin that converts path commands for an SVG path to polygonal points.

I found one : https://github.com/Phrogz/svg-path-to-polygons

The problem here is it does not support arcs and curves like A and C.

let pathData = 'M5,15 c5.5,0 10-4.5 10,-10 h10';
let points = pathDataToPolys(pathData, {tolerance:1, decimals:1});
console.log(points);
/*******************************************************************
[
  [ [5,15],[7,14.8],[10.6,13.3],[13.3,10.6],[14.8,7],[15,5],[25,5] ]
]

I have path as 'M0 0 H50 A20 20 0 1 0 100 50 v25 C50 125 0 85 0 85 z'. I need this to be converted to polygon points.

Any help or suggestions highly appreciated.

like image 342
user10519853 Avatar asked Jan 01 '23 14:01

user10519853


1 Answers

I think there is some confusion because it is not clear what sort of conversion you are looking for. There are two solutions with different levels of difficulty.

  1. Flattening. Flattening is a term used by 2D renderers for a step in the process of rendering. The flattening algorithm is adaptive. It will space the polygon points closer together when the path has a high curvature. And it will use fewer points when the path is straighter.

  2. Simple conversion. You can just step along the curve at regular intervals and sample the path location at each step.

The example code and output, you provide in your question, makes it look like you want the Flattening type.

However, if you are not fussy, then option 2 is really easy. SVG includes an API designed for this task.

var NUM_POINTS = 6;

var path = document.getElementById("test");
var len = path.getTotalLength();
var points = [];

for (var i=0; i < NUM_POINTS; i++) {
    var pt = path.getPointAtLength(i * len / (NUM_POINTS-1));
    points.push([pt.x, pt.y]);
}

console.log("points = ", points);
<svg>
  <path id="test" d="M5,15 c5.5,0 10-4.5 10,-10 h10"/>
</svg>
like image 134
Paul LeBeau Avatar answered Jan 04 '23 05:01

Paul LeBeau