Get SVG from canvas element and save it Get SVG from canvas element and save it javascript javascript

Get SVG from canvas element and save it


If you want to preserve it as a vector graphic instead of as a raster, you can try one of the libraries that translate the canvas API operations to svg.

For SVGKit:

var svgkitContext = new SVGCanvas(150,150);function draw(ctx) {   // ... normal canvas drawing commands go here ...}// draw to SVGKit canvas (svg) instead of canvasElement.getContext("2d")draw(svgkitContext);

Full running example of the above.

For canvas-svg:

var canvasSVGContext = new CanvasSVG.Deferred();canvasSVGContext.wrapCanvas(document.querySelector("canvas"));var canvasContext = document.querySelector("canvas").getContext("2d");function draw(ctx) {    // ... normal canvas drawing commands go here ...}// draw to html5 canvas and record as svg at the same timedraw(canvasContext);// append the svg resultvar svg = document.appendChild(canvasContext.getSVG());

Full running example of the above.

For generating svg instead:

Another option is of course to make the graph as an svg in the first place, d3.js is a javascript library that makes it easy to do this, see e.g this example of a force directed graph.


If you're limited to ImageData you're out of luck, because that's just a mere pixel array (see reference). You can't obtain a meaningful SVG image from there. You can probably pull off a .png representation...but that's a static image with no interaction.

If you're going to do some sort of canvas to SVG export, it's important how you're doing the canvas drawing. The best approach would be to use a library that maintains a canvas scene graph.

Fabric.js seems to be a good choice. You can do the drawing with canvas and then call canvas.toSVG() and get your svg image.