Last active
April 27, 2024 16:33
-
-
Save camman3d/314c07def1d6f728cd89ce0f49fc0ed1 to your computer and use it in GitHub Desktop.
Convert SVG to PNG. Verified in Chrome, Safari, and Firefox
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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