-
-
Save nkint/ac1d3ca336463e519ca40ac867ae5b6b 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
import defined from 'defined' | |
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 => { | |
return shape.lines.map(line => { | |
const svgPath = 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 ') | |
}).join('\n\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>` | |
} | |
export function shapesToCanvas() { | |
shapes.forEach(({ lines, strokeStyle }) => { | |
lines.forEach(line => { | |
context.beginPath() | |
context.strokeStyle = strokeStyle | |
line.forEach(p => context.lineTo(p[0], p[1])) | |
context.stroke() | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment