Skip to content

Instantly share code, notes, and snippets.

@jarek-foksa
Created December 13, 2017 00:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jarek-foksa/8ce77a6792bc09139398ca95b05e7a8b to your computer and use it in GitHub Desktop.
Save jarek-foksa/8ce77a6792bc09139398ca95b05e7a8b to your computer and use it in GitHub Desktop.
// @info
// Takes normalized path data and harmonizes it so that each subpath starts with "M" seg, followed by one or
// more "C" or "L" segs, optionally followed by "Z" seg.
let harmonizePathData = (pathData) => {
if (!pathData.find(($0) => $0.type === "C" || $0.type === "L")) return [];
let simplifiedPathData = [];
let lastType = null;
let currentX = 0;
let currentY = 0;
let subpathX = 0;
let subpathY = 0;
for (let seg of pathData) {
if (seg.type === "M") {
// M is redundant if it is followed by another M
if (lastType === "M") {
simplifiedPathData.pop();
}
simplifiedPathData.push(seg);
currentX = seg.values[0];
currentY = seg.values[1];
subpathX = seg.values[0];
subpathY = seg.values[1];
}
else if (seg.type === "L") {
// Insert explicit M if the last seg is Z
if (lastType === "Z") {
simplifiedPathData.push({type: "M", values: [subpathX, subpathY]});
}
simplifiedPathData.push(seg);
currentX = seg.values[0];
currentY = seg.values[1];
}
else if (seg.type === "C") {
// Insert explicit M if the last seg is Z
if (lastType === "Z") {
simplifiedPathData.push({type: "M", values: [subpathX, subpathY]});
}
simplifiedPathData.push(seg);
currentX = seg.values[4];
currentY = seg.values[5];
}
else if (seg.type === "Z") {
// Insert explicit L if the subpath is not closed
if (currentX !== subpathX || currentY !== subpathY) {
simplifiedPathData.push({type: "L", values: [subpathX, subpathY]});
}
simplifiedPathData.push(seg);
currentX = subpathX;
currentY = subpathY;
}
lastType = seg.type;
}
return simplifiedPathData;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment