I'm trying to download a SVG image to PNG, using Canvas.
The process I'm using as follows:
- Get the SVG HTML;
- Convert the SVG to Canvas;
- Download the Canvas as PNG.
Here's my code:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var data = document.getElementById("mySvg");
var elementWidth = data.clientWidth || data.parentNode.clientWidth;
var elementHeight = data.clientHeight || data.parentNode.clientHeight;
var DOMURL = window.URL || window.webkitURL || window;
var aLines = document.createElement("a");
var img = new Image();
var svg = new Blob([data.outerHTML], {
type: 'image/svg+xml'
});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
}
img.src = url;
aLines.href = canvas.toDataURL();
aLines.download = "test.png";
aLines.click();
<!-- Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Drawing_DOM_objects_into_a_canvas -->
<canvas id="canvas" style="border:2px solid black;" width="200" height="200">
</canvas>
<svg id="mySvg" xmlns="http://www.w3.org/2000/svg" width="200" height="200">
<foreignObject width="100%" height="100%">
<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">
<em>I</em> like
<span style="color:white; text-shadow:0 0 2px blue;">
cheese</span>
</div>
</foreignObject>
</svg>
When I execute that code, instead of getting the image with the contents of the SVG, I'm getting a black image.
I've tried to change the Canvas background to white, but then I get a blank image and no SVG contents.
Do you have any suggestions to fix this problem or can you point me in the right direction?
Thank you.