-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcanvas-to-svg.js
51 lines (48 loc) · 1.35 KB
/
canvas-to-svg.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const canvasSketch = require("canvas-sketch");
const Canvas2SVG = require("canvas2svg");
const Color = require("canvas-sketch-util/color");
module.exports = canvasToSVG;
function canvasToSVG(sketch) {
const obj = typeof sketch === "function" ? {} : sketch;
const render = typeof sketch === "function" ? sketch : obj.render;
return {
...obj,
render(props) {
render(props);
if (props.exporting && !props.recording) {
return [props.canvas, serialize(render, props)];
}
},
};
}
function fix(node, name) {
if (!node.hasAttribute(name) || !node.getAttribute(name)) return;
const attr = node.getAttribute(name);
const parsed = Color.parse(attr);
if (parsed) node.setAttribute(name, parsed.hex);
}
function serialize(draw, props) {
const {
canvasWidth,
canvasHeight,
width,
height,
units,
scaleX,
scaleY,
} = props;
const context = new Canvas2SVG(canvasWidth, canvasHeight);
draw({ ...props, context });
const svg = context.getSvg().cloneNode(true);
svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
[...svg.querySelectorAll("*")].forEach((node) => {
fix(node, "fill");
fix(node, "stroke");
});
svg.setAttribute("width", width + units);
svg.setAttribute("height", height + units);
return {
data: new XMLSerializer().serializeToString(svg),
extension: ".svg",
};
}