Skip to content

Instantly share code, notes, and snippets.

@Akiyamka
Last active December 3, 2018 10:01
Show Gist options
  • Save Akiyamka/4b3c1c21277a8869aa9f28b5ab5494b3 to your computer and use it in GitHub Desktop.
Save Akiyamka/4b3c1c21277a8869aa9f28b5ab5494b3 to your computer and use it in GitHub Desktop.
svg path parser
function createSVG(d) {
const xmlns = "http://www.w3.org/2000/svg";
const boxWidth = 300;
const boxHeight = 300;
const svgElem = document.createElementNS(xmlns, "svg");
svgElem.setAttributeNS(null, "viewBox", "0 0 " + boxWidth + " " + boxHeight);
svgElem.setAttributeNS(null, "width", boxWidth);
svgElem.setAttributeNS(null, "height", boxHeight);
svgElem.setAttributeNS(null, "fill", "none");
svgElem.style.display = "block";
const path = document.createElementNS(xmlns, "path");
path.setAttributeNS(null, "stroke", "white");
path.setAttributeNS(null, "d", d);
svgElem.appendChild(path)
return svgElem;
};
const path = [
{ M: [ '40.5', '88' ] },
{ L: [ '40.5', '24.658' ] },
{ C: [ '40.5', '22.1569', '38.9485', '19.9182', '36.6067', '19.04' ] },
{ L: [ '4.39326', '6.95997' ] },
{ C: [ '2.05143', '6.08179', '0.499996', '3.84306', '0.499996', '1.342' ] },
{ L: [ '0.499996', '0' ] }
];
document.getElementById("app")
.appendChild(createSVG(makePath(path)));
const path = [
{ M: [ '40.5', '88' ] },
{ L: [ '40.5', '24.658' ] },
{ C: [ '40.5', '22.1569', '38.9485', '19.9182', '36.6067', '19.04' ] },
{ L: [ '4.39326', '6.95997' ] },
{ C: [ '2.05143', '6.08179', '0.499996', '3.84306', '0.499996', '1.342' ] },
{ L: [ '0.499996', '0' ] }
];
const p = 'M40.5 88L40.5 24.658C40.5 22.1569 38.9485 19.9182 36.6067 19.04L4.39326 6.95997C2.05143 6.08179 0.499996 3.84306 0.499996 1.342L0.499996 0';
function makePath(path) {
return path.reduce((result, param) => {
const [type, coords] = Object.entries(param)[0]
return result + type + coords.join(' ');
}, '')
}
function parsePath(p) {
return p.match(/[A-Z](\d|\.|\s)+/g).map(i => {
const opt = i.split(' ');
const key = opt[0][0];
opt[0] = opt[0].slice(1);
return { [key]: opt }
})
}
@Akiyamka
Copy link
Author

Akiyamka commented Dec 3, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment