Quantcast
Channel: Convert SVG to image (JPEG, PNG, etc.) in the browser - Stack Overflow
Viewing all articles
Browse latest Browse all 17

Answer by Alex Vovchuk for Convert SVG to image (JPEG, PNG, etc.) in the browser

$
0
0

Svg to png can be converted depending on conditions:

  1. If svg is in format SVG (string) paths:
  • create canvas
  • create new Path2D() and set svg as parameter
  • draw path on canvas
  • create image and use canvas.toDataURL() as src.

example:

const canvas = document.createElement('canvas');const ctx = canvas.getContext('2d');let svgText = 'M10 10 h 80 v 80 h -80 Z';let p = new Path2D('M10 10 h 80 v 80 h -80 Z');ctx.stroke(p);let url = canvas.toDataURL();const img = new Image();img.src = url;

Note that Path2D not supported in ie and partially supported in edge. Polyfill solves that:https://github.com/nilzona/path2d-polyfill

  1. Create svg blob and draw on canvas using .drawImage():
  • make canvas element
  • make a svgBlob object from the svg xml
  • make a url object from domUrl.createObjectURL(svgBlob);
  • create an Image object and assign url to image src
  • draw image into canvas
  • get png data string from canvas: canvas.toDataURL();

Nice description:https://web.archive.org/web/20200125162931/http://ramblings.mcpher.com:80/Home/excelquirks/gassnips/svgtopng

Note that in ie you will get exception on stage of canvas.toDataURL(); It is because IE has too high security restriction and treats canvas as readonly after drawing image there. All other browsers restrict only if image is cross origin.

  1. Use canvg JavaScript library. It is separate library but has useful functions.

Like:

ctx.drawSvg(rawSvg);var dataURL = canvas.toDataURL();

Viewing all articles
Browse latest Browse all 17

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>