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

// https://stackoverflow.com/questions/27230293/how-to-draw-an-inline-svg-in-dom-to-a-canvas
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.
 // https://stackoverflow.com/questions/27863617/is-it-possible-to-copy-a-canvas-image-to-the-clipboard
function copyToClipboard(canvas) {
  console.log('copying');
  canvas.toBlob(function (blob) {
    const item = new ClipboardItem({ 'image/png': blob });
    navigator.clipboard.write([item]);
  });
}

  

Putting it together

Here is the image as inline SVG markup:

image/svg+xml

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 () {
   copyToClipboard(canvas);
 });
}

main()
  

Previously

Next