Converting SVG to PNG using Canvas element

This image is a canvas element with an SVG image drawn onto it. When you click the "copy" button, the image is copied to your clipboard as a PNG file.

Drawing to the canvas element

Get the SVG image and draw it to a canvas element

function drawInlineSVG(svgElement, ctx) {
  var svgURL = new XMLSerializer().serializeToString(svgElement);
  var img = new Image();
  img.onload = function () {
    ctx.drawImage(this, 0, 0);
  img.src = 'data:image/svg+xml; charset=utf8, ' + encodeURIComponent(svgURL);

Canvas to PNG to Clipboard

And a function to copy the Canvas contents to the clipboard as a PNG file.
function copyToClipboard(canvas) {
  canvas.toBlob(function (blob) {
    const item = new ClipboardItem({ 'image/png': blob });


Putting it together

Here is the image as inline SVG markup:


And here is the code to select the DOM elements, call our functions and add an event listener to the "Copy" button.

function main() {
 let myImage = document.getElementById('my-image');
 let canvas = document.getElementById('my-canvas');
 canvas.width = 200;
 canvas.height = 220;
 const ctx = canvas.getContext('2d');
 drawInlineSVG(myImage, ctx);
 const btn = document.getElementById('copy-button');
 btn.addEventListener('click', function () {