Convert SVG to image (JPEG, PNG, WEBP) in the browser (JavaScript)

Last updated:16th Aug 2022

Convert SVG to image (JPEG, PNG, WEBP) in the browser (JavaScript)

This article will convert SVG images to PNG, JPG, and WEBP format using javascript. after converting you can download the image by clicking on the download link URL.

To understand this example, you should have knowledge of javascript promise, XMLSerializer, and DOM.


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>convert SVG images to PNG, JPG, and WEBP format</title>
</head>

<body>
    <div id="svg_container" style="float: left; width: 50%">
        <svg width="200" height="200" viewBox="-100 -100 200 200">
            <circle cx="0" cy="20" r="70" fill="#D1495B" />
            <circle cx="0" cy="-75" r="12" fill="none" stroke="#F79257" stroke-width="2" />
            <rect x="-17.5" y="-65" width="35" height="20" fill="#F79257" />
        </svg>
    </div>
    <div>
        <button id="map2Png">PNG</button>
        <button id="map2Jpg">JPG</button>
        <button id="map2Webp">WEBP</button>
    </div>

    <div id="img_download_btn"></div>


<script>
const waitForImage = imgElem => new Promise(resolve => imgElem.complete ? resolve() : imgElem.onload = imgElem.onerror = resolve);

const svgToImgDownload = ext => {
  if (!['png', 'jpg', 'webp'].includes(ext))
    return;
  const _svg = document.querySelector("#svg_container").querySelector('svg');
  const xmlSerializer = new XMLSerializer();
  let _svgStr = xmlSerializer.serializeToString(_svg);
  const img = document.createElement('img');
  img.src = 'data:image/svg+xml;base64,' + window.btoa(_svgStr);
  waitForImage(img)
    .then(_ => {
      const canvas = document.createElement('canvas');
      canvas.width = _svg.clientWidth;
      canvas.height = _svg.clientHeight;
      canvas.getContext('2d').drawImage(img, 0, 0, _svg.clientWidth, _svg.clientHeight);
      return canvas.toDataURL('image/' + (ext == 'jpg' ? 'jpeg' : ext), 1.0);
    })
    .then(dataURL => {
      console.log(dataURL);
      document.querySelector("#img_download_btn").innerHTML = `<a href="${dataURL}" download="img.${ext}">Download</a>`;
    })
    .catch(console.error);
};

document.querySelector('#map2Png').addEventListener('click', _ => svgToImgDownload('png'));
document.querySelector('#map2Jpg').addEventListener('click', _ => svgToImgDownload('jpg'));
document.querySelector('#map2Webp').addEventListener('click', _ => svgToImgDownload('webp'));
</script>
</body>

</html>
Run now