Skip to content

Instantly share code, notes, and snippets.

@netsi1964
Last active June 14, 2017 07:00
Show Gist options
  • Save netsi1964/9331fd445ffa08c681c0c71500394d0f to your computer and use it in GitHub Desktop.
Save netsi1964/9331fd445ffa08c681c0c71500394d0f to your computer and use it in GitHub Desktop.
SVG Path manipulation
{
"ele": {},
"commands": [
{
"cmd": "M",
"data": [
75.6,
35.3
]
},
{
"cmd": "L",
"data": [
77.4,
34.2
]
},
{
"cmd": "L",
"data": [
100.4,
25.8
]
},
{
"cmd": "L",
"data": [
75.6,
35.3
]
},
{
"cmd": "Z"
}
]
}
var path = document.querySelector("path");
function getPathCommands(pathElement) {
var data = pathElement.getAttribute("d");
var ofs = 0;
var indexes = data.match(/[hvmlcqtsaz]/gi).map(function(cmd, i) {
ofs += data.substr(ofs).indexOf(cmd) + 1;
return ofs - 1;
});
var commands = [];
indexes.map(function(curr, i) {
var raw = data.substr(
curr,
i < indexes.length - 1 ? indexes[i + 1] - curr : data.length
);
var cmd = {
cmd: raw.substr(0, 1)
};
var attr = raw.substr(1, raw.length).split(/[ ,]/ig);
if (attr.length>1) {
attr = attr.map(function(val) {
return parseFloat(val);
})
cmd["data"] = attr;
}
commands.push(cmd);
});
return {ele:pathElement, commands:commands};
}
getPathCommands(path);
Display the source blob
Display the rendered blob
Raw
<svg width="100%" height="100%" viewBox="0 0 1679 1662" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve">
<path d="M75.6,35.3L77.4,34.2L100.4,25.8L75.6,35.3Z"/>
</svg>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment