Skip to content

Instantly share code, notes, and snippets.

Created September 4, 2017 20:31
What would you like to do?
Converts a svg element into a png image instance
* @param {SVGSVGElement} svg
* @param {Number} [w] Width of png image. Default: 128
* @param {Number} [h] Height of png image. Default: 128
* @return {Image} png image
const svg2png = (svg, w=128, h=128) => {
svg.setAttribute('width', `${w}px`);
svg.setAttribute('height', `${h}px`);
const xml = new XMLSerializer().serializeToString(svg);
const data = `data:image/svg+xml;base64,${btoa(xml)}`;
const img = new Image();
img.setAttribute('src', data);
return img;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment