Instantly share code, notes, and snippets.

Embed
What would you like to do?
svg path to polygon (doesn't support curve segments, only LlMmHhVvZz, assumes commands are space separated!)
const d =
  "M 12.773125,113.36602 221.3132,95.992053 l 12.11088,1.651482 10.58724,6.605925 7.48176,8.10713 2.84979,11.98594 -1.51508,13.41407 -4.62098,9.90131 -9.00254,8.33802 -9.58241,3.43426 -12.70975,0.58031 -203.961053,-17.77707 -5.9080342,-2.37991 -3.4503706,-4.50127 -1.9267305,-6.60592 1.1009889,-7.00904 3.5114276,-5.52164 z";
const p = svgDToPoly(d);

p would then be

[
  [233.42408, 97.643535],
  [244.01132, 104.24946],
  [251.49308000000002, 112.35659],
  [254.34287000000003, 124.34253],
  [252.82779000000002, 137.7566],
  [248.20681000000002, 147.65791],
  [239.20427, 155.99593],
  [229.62186, 159.43018999999998],
  [216.91210999999998, 160.01049999999998],
  [12.951056999999992, 142.23342999999997],
  [7.043022799999991, 139.85351999999997],
  [3.5926521999999914, 135.35224999999997],
  [1.6659216999999915, 128.74632999999997],
  [2.7669105999999912, 121.73728999999997],
  [6.278338199999991, 116.21564999999997],
  [233.42408, 97.643535]
]

Try it out here

Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
(function(global) {
const supportedCommands = "MmlLHhVvZz".split("");
const absoluteCommands = "MLHVZ".split("");
const singleNumberCommands = "HhVv".split("");
function contains(arr, el) {
return arr.indexOf(el) !== -1;
}
function startsWithNumber(s) {
return /^-?\d/.test(s);
}
function svgDToPoly(d) {
const parts = d.split(" ");
let p = [0, 0];
let absolute = true;
let volatile = false;
const points = [];
let part;
let lastCommand;
while ((part = parts.shift())) {
if (contains(supportedCommands, part)) {
absolute = contains(absoluteCommands, part);
volatile = part === "m" || part === "M";
lastCommand = part;
if (part === "Z" || part === "z") {
points.push([points[0][0], points[0][1]]);
}
} else if (startsWithNumber(part)) {
const arr = part.split(",").map(parseFloat);
if (contains(singleNumberCommands, part)) {
const num = parseFloat(parts.shift());
if (part === "H" || part === "h") {
points.push([p[0], (part === "h" ? p[1] : num) + num]);
} else if (part === "V" || part === "v") {
points.push([(part === "v" ? p[0] : 0) + num, p[1]]);
}
}
// MmLl
if (absolute) {
p = arr;
} else {
p = [p[0] + arr[0], p[1] + arr[1]];
}
if (!volatile) {
points.push(p);
}
} else {
throw part;
}
}
return points;
}
global.svgDToPoly = svgDToPoly;
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment