To convert an SVG to PNG using JavaScript, you can utilize the <canvas>
element and the toDataURL()
method. Here’s an example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<svg id="my-svg" width="200" height="200">
<rect x="50" y="50" width="100" height="100" fill="red" />
</svg>
<button onclick="convertSVGToPNG()">Convert to PNG</button>
<script>
function convertSVGToPNG() {
const svgElement = document.getElementById('my-svg');
const svgString = new XMLSerializer().serializeToString(svgElement);
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
const dataURL = canvas.toDataURL('image/png');
const link = document.createElement('a');
link.href = dataURL;
link.download = 'filename.png';
link.click();
};
img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgString)));
}
</script>
</body>
</html>
In the above example, we have an SVG element with an id of my-svg
and a button with an onclick
event that triggers the convertSVGToPNG()
function.
Inside the function, we select the SVG element using document.getElementById()
. We then serialize the SVG element to a string using XMLSerializer().serializeToString()
.
Next, we create a <canvas>
element using document.createElement()
and get its 2D rendering context using getContext('2d')
.
We create an <img>
element and set its onload
event handler. Inside the event handler, we set the canvas dimensions to match the image dimensions and draw the image onto the canvas using ctx.drawImage()
.
Then, we use canvas.toDataURL('image/png')
to convert the canvas content to a PNG data URL.
Finally, we create a <a>
element dynamically, set its href
attribute to the data URL, the download
attribute to the desired filename for the downloaded PNG file, and trigger a click event on the link using link.click()
.
When the user clicks the “Convert to PNG” button, the SVG will be converted to a PNG image and downloaded with the specified filename.
Note that this method may have limitations due to cross-origin restrictions. If the SVG 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 SVG to PNG conversion, such as canvg or svg2img.