Skip to content

Instantly share code, notes, and snippets.

@maruware
Created July 23, 2019 09:29
Show Gist options
  • Save maruware/c98b3b6627cdfe5aec02ce431ba14f03 to your computer and use it in GitHub Desktop.
Save maruware/c98b3b6627cdfe5aec02ce431ba14f03 to your computer and use it in GitHub Desktop.
SVG to PNG through Canvas
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