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

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

$
0
0

There are several ways to convert SVG to PNG using the Canvg library.

In my case, I needed to get the PNG blob from inline SVG.

The library documentation provides an example (see OffscreenCanvas example).

But this method does not work at the moment in Firefox. Yes, you can enable the gfx.offscreencanvas.enabled option in the settings. But will every user on the site do this? :)

However, there is another way that will work in Firefox too.

const el = document.getElementById("some-svg"); //this is our inline SVGvar canvas = document.createElement('canvas'); //create a canvas for the SVG rendercanvas.width = el.clientWidth; //set canvas sizescanvas.height = el.clientHeight;const svg = new XMLSerializer().serializeToString(el); //convert SVG to string//render SVG inside canvasconst ctx = canvas.getContext('2d');const v = await Canvg.fromString(ctx, svg);await v.render();let canvasBlob = await new Promise(resolve => canvas.toBlob(resolve));

For the last line thanks to this answer


Viewing all articles
Browse latest Browse all 17

Trending Articles



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