Skip to content

Instantly share code, notes, and snippets.

@ycmjason
Last active March 26, 2025 10:50
Show Gist options
  • Select an option

  • Save ycmjason/1570f2ae6588be753053ca874d71b64b to your computer and use it in GitHub Desktop.

Select an option

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.
// 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 */
});
@ycmjason
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment