Skip to content

Instantly share code, notes, and snippets.

@balint42
Last active March 28, 2021 20:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save balint42/934fff4d19a6c4668075 to your computer and use it in GitHub Desktop.
Save balint42/934fff4d19a6c4668075 to your computer and use it in GitHub Desktop.
parse svg path javascript function

JS function for parsing SVG paths

Parse an svg path object and generate an Array of path commands. Each command is an Array of the form [command, arg1, arg2, ...] NOTE: parsing is done via pathSegList which is faster and more reliable than parsing the path string directly, but might not work in old browsers.

/**
* @brief Parse an svg path object and return commands
* Parse an svg path object and generate an Array of path commands.
* Each command is an Array of the form `[command, arg1, arg2, ...]`
* NOTE: parsing is done via "pathSegList" which is faster and more
* reliable than parsing the path string directly, but might not
* work in old browsers.
*
* @author Balint Morvai <balint@morvai.de>
* @license http://en.wikipedia.org/wiki/MIT_License MIT License
* @param {Object} path object
* @return {Array}
*/
function parsePath(path) {
var list = path.pathSegList;
var res = [];
for(var i = 0; i < list.length; i++) {
var cmd = list[i].pathSegTypeAsLetter;
var sub = [];
switch(cmd) {
case "C":
case "c":
sub.unshift(list[i].y2); sub.unshift(list[i].x2);
case "Q":
case "q":
sub.unshift(list[i].y1); sub.unshift(list[i].x1);
case "M":
case "m":
case "L":
case "l":
sub.push(list[i].x); sub.push(list[i].y);
break;
case "A":
case "a":
sub.push(list[i].r1); sub.push(list[i].r2);
sub.push(list[i].angle);
sub.push(list[i].largeArcFlag);
sub.push(list[i].sweepFlag);
sub.push(list[i].x); sub.push(list[i].y);
break;
case "H":
case "h":
sub.push(list[i].x);
break;
case "V":
case "v":
sub.push(list[i].y);
break;
case "S":
case "s":
sub.push(list[i].x2); sub.push(list[i].y2);
sub.push(list[i].x); sub.push(list[i].y);
break;
case "T":
case "t":
sub.push(list[i].x); sub.push(list[i].y);
break;
}
sub.unshift(cmd);
res.push(sub);
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment