Created
August 21, 2017 15:17
-
-
Save mattdesl/1e363da31583c735fa711b1b74f8c95a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const TO_PX = 35.43307; | |
const DEFAULT_SVG_LINE_WIDTH = 0.03; | |
export function shapesToSVG (shapes, opt = {}) { | |
const dimensions = opt.dimensions; | |
if (!dimensions) throw new TypeError('must specify dimensions currently'); | |
const decimalPlaces = 5; | |
const viewWidth = (dimensions[0] * TO_PX).toFixed(decimalPlaces); | |
const viewHeight = (dimensions[1] * TO_PX).toFixed(decimalPlaces); | |
const paths = shapes.map(shape => { | |
const svgPath = shape.line.map((point, j) => { | |
const type = (j === 0) ? 'M' : 'L'; | |
const x = (TO_PX * point[0]).toFixed(decimalPlaces); | |
const y = (TO_PX * point[1]).toFixed(decimalPlaces); | |
return `${type} ${x} ${y}`; | |
}).join(' '); | |
const fillStyle = shape.fillStyle || 'none'; | |
const strokeStyle = shape.strokeStyle || 'black'; | |
const lineWidth = defined(shape.lineWidth, DEFAULT_SVG_LINE_WIDTH); | |
const alpha = defined(shape.alpha, 1); | |
const lineCap = defined(shape.lineCap, 'round'); | |
const lineJoin = defined(shape.lineJoin, 'round'); | |
return `<path d="${svgPath}" stroke-linecap="${lineCap}" stroke-linejoin="${lineJoin}" opacity="${alpha}" fill="${fillStyle}" stroke="${strokeStyle}" stroke-width="${lineWidth}cm" />`; | |
}).join('\n'); | |
return `<?xml version="1.0" standalone="no"?> | |
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" | |
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> | |
<svg width="${dimensions[0]}cm" height="${dimensions[1]}cm" | |
xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 ${viewWidth} ${viewHeight}"> | |
<g> | |
${paths} | |
</g> | |
</svg>`; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using with:
and with canvas:
Just an idea: why does a shape have only one line?
( see here: https://gist.github.com/nkint/ac1d3ca336463e519ca40ac867ae5b6b )