Last active
March 26, 2025 10:50
-
-
Save ycmjason/1570f2ae6588be753053ca874d71b64b to your computer and use it in GitHub Desktop.
A more modern way to convert svg to png/jpeg and obtain the data uri.
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
| // https://github.com/ycmjason/svg-to-img | |
| const getImageDataURL = (image, type = 'png') => { | |
| // pre: image is loaded | |
| if (type === 'jpg') type = 'jpeg'; | |
| const { width, height } = image; | |
| const canvas = document.createElement('canvas'); | |
| const context = canvas.getContext('2d'); | |
| canvas.width = width; | |
| canvas.height = height; | |
| if (type === 'jpeg') { | |
| context.fillStyle = 'white'; | |
| context.fillRect(0, 0, width, height); | |
| } | |
| context.drawImage(image, 0, 0, width, height); | |
| return canvas.toDataURL(`image/${type}`); | |
| }; | |
| const convertSvg = (svgString, type = 'png') => new Promise((res, rej) => { | |
| const image = new Image(); | |
| image.onload = () => res(getImageDataURL(image, type)); | |
| image.src = `data:image/svg+xml,${encodeURIComponent(svgString)}`; | |
| }); | |
| convertSvg('<svg>...</svg>', 'png').then(dataURL => { | |
| /* do something with it */ | |
| }); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
deployed on https://glittering-smakager-3f021e.netlify.app/