svg-to-png.js
33 lines
| 1 | async function svgToPng(svgElement) { |
| 2 | // 1. Get SVG data |
| 3 | const svgData = new XMLSerializer().serializeToString(svgElement); |
| 4 | const svgBlob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' }); |
| 5 | const url = URL.createObjectURL(svgBlob); |
| 6 | |
| 7 | // 2. Load SVG into image (wrapped in promise) |
| 8 | const img = await new Promise((resolve, reject) => { |
| 9 | const image = new Image(); |
| 10 | image.onload = () => resolve(image); |
| 11 | image.onerror = reject; |
| 12 | image.src = url; |
| 13 | }); |
| 14 | |
| 15 | // 3. Create canvas and draw |
| 16 | const canvas = document.createElement('canvas'); |
| 17 | canvas.width = svgElement.width.baseVal.value || svgElement.getBoundingClientRect().width; |
| 18 | canvas.height = svgElement.height.baseVal.value || svgElement.getBoundingClientRect().height; |
| 19 | |
| 20 | const ctx = canvas.getContext('2d'); |
| 21 | ctx.drawImage(img, 0, 0); |
| 22 | |
| 23 | URL.revokeObjectURL(url); |
| 24 | |
| 25 | // 4. Create PNG image element |
| 26 | const pngImage = new Image(); |
| 27 | pngImage.src = canvas.toDataURL('image/png'); |
| 28 | |
| 29 | return pngImage; |
| 30 | } |
| 31 | |
| 32 | module.exports = { svgToPng } |
| 33 |