Skip to content

Instantly share code, notes, and snippets.

@camman3d
Last active April 27, 2024 16:33
Show Gist options
  • Save camman3d/314c07def1d6f728cd89ce0f49fc0ed1 to your computer and use it in GitHub Desktop.
Save camman3d/314c07def1d6f728cd89ce0f49fc0ed1 to your computer and use it in GitHub Desktop.
Convert SVG to PNG. Verified in Chrome, Safari, and Firefox
// let svg = document.querySelector('svg');
function svgToPng(svg) {
let svgData = new XMLSerializer().serializeToString(svg);
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
let DOMURL = window.URL || window.webkitURL || window;
let img = new Image();
let blog = new Blob([svgData], {type: 'image/svg+xml'});
let url = DOMURL.createObjectURL(blog);
return new Promise(resolve => {
img.addEventListener('load', () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
let url = canvas.toDataURL('image/png');
resolve(url);
});
img.src = url;
});
}
@GunGunGun
Copy link

Very nice, confirmed work with width and height as pixel, not percentage in Firefox!

Fixed by using this: https://stackoverflow.com/questions/76232792/converting-svg-to-png-without-knowing-the-width-and-height

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment