Skip to content

Instantly share code, notes, and snippets.

@carlosascari
Created September 4, 2017 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlosascari/9999ff4bc43c93fd714b4dd063f083a7 to your computer and use it in GitHub Desktop.
Save carlosascari/9999ff4bc43c93fd714b4dd063f083a7 to your computer and use it in GitHub Desktop.
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