Svg To Image Download

by Umair Khan

HTML

<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>

JavaScript

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'));