To export a canvas to an SVG file using JavaScript, you can convert the canvas content to an SVG string and then save it as a file. Here’s an example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<canvas id="my-canvas" width="200" height="200"></canvas>
<button onclick="exportCanvasToSVG()">Export to SVG</button>
<script>
function exportCanvasToSVG() {
const canvas = document.getElementById('my-canvas');
const ctx = canvas.getContext('2d');
const svgString = `<svg xmlns="http://www.w3.org/2000/svg" width="${canvas.width}" height="${canvas.height}">
<foreignObject width="100%" height="100%">
<div xmlns="http://www.w3.org/1999/xhtml">
<style>
/* Add your canvas styles here */
canvas {
background-color: white;
}
</style>
${canvas.outerHTML}
</div>
</foreignObject>
</svg>`;
const blob = new Blob([svgString], { type: 'image/svg+xml' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'canvas.svg';
link.click();
URL.revokeObjectURL(url);
}
</script>
</body>
</html>
In the above example, we have a canvas element with an id of my-canvas
and a button with an onclick
event that triggers the exportCanvasToSVG()
function.
Inside the function, we select the canvas element using document.getElementById()
and get its 2D rendering context using getContext('2d')
.
We then create an SVG string that wraps the canvas content using the <svg>
and <foreignObject>
elements. The canvas content is embedded within a <div>
element inside the <foreignObject>
. You can add custom styles to the <style>
element within the <div>
to customize the appearance of the canvas in the exported SVG.
Next, we create a Blob
object with the SVG string and specify the MIME type as 'image/svg+xml'
. We then create a URL for the blob using URL.createObjectURL()
.
After that, we create a <a>
element dynamically using document.createElement()
. We set the href
attribute to the URL of the blob, the download
attribute to the desired filename for the exported SVG file, and trigger a click event on the link using link.click()
.
Finally, we revoke the URL using URL.revokeObjectURL()
to release the resources associated with the URL.
When the user clicks the “Export to SVG” button, the canvas content will be converted to an SVG file and downloaded with the specified filename.
Note that this method may have limitations due to cross-origin restrictions. If the canvas content is loaded from a different domain, you may encounter security errors. In such cases, you may need to use a server-side solution or a library that supports canvas to SVG conversion, such as fabric.js or canvg.