Skip to content

Instantly share code, notes, and snippets.

@mattdesl
Created August 21, 2017 15:17
Show Gist options
  • Save mattdesl/1e363da31583c735fa711b1b74f8c95a to your computer and use it in GitHub Desktop.
Save mattdesl/1e363da31583c735fa711b1b74f8c95a to your computer and use it in GitHub Desktop.
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>`;
}
@nkint
Copy link

nkint commented Aug 24, 2017

Using with:

shapes = [
  { line: [ [ 2, 3 ], [ 4, 2 ], [ 3, 2 ] ], strokeStyle: 'blue', lineWidth: 0.1 }
]

and with canvas:

  function draw() {
    shapes.forEach(({ line, strokeStyle }) => {
      context.beginPath()
      context.strokeStyle = strokeStyle
      line.forEach(p => context.lineTo(p[0], p[1]))
      context.stroke()
    })
  }

Just an idea: why does a shape have only one line?
( see here: https://gist.github.com/nkint/ac1d3ca336463e519ca40ac867ae5b6b )

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