Created
July 23, 2019 09:29
-
-
Save maruware/c98b3b6627cdfe5aec02ce431ba14f03 to your computer and use it in GitHub Desktop.
SVG to PNG through Canvas
This file contains 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
export const svgToPng = async (svg: SVGSVGElement) => { | |
const w = svg.getAttribute('width') | |
const h = svg.getAttribute('height') | |
if (!w || !h) { | |
throw new Error('Undefined svg size') | |
} | |
const width = parseInt(w) | |
const height = parseInt(h) | |
const ser = new XMLSerializer() | |
const svgAsXML = ser.serializeToString(svg) | |
const canvas = document.createElement('canvas') | |
const ctx = canvas.getContext('2d') | |
if (!ctx) { | |
throw new Error('Failed to get context') | |
} | |
const loader = document.createElement('img') | |
loader.width = canvas.width = width | |
loader.height = canvas.height = height | |
return new Promise<string>(resolve => { | |
loader.onload = () => { | |
ctx.drawImage(loader, 0, 0, loader.width, loader.height) | |
resolve(canvas.toDataURL()) | |
} | |
loader.src = 'data:image/svg+xml,' + encodeURIComponent(svgAsXML) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment