Skip to content

Instantly share code, notes, and snippets.

@ycmjason ycmjason/conver-svg.js
Last active Jun 29, 2018

Embed
What would you like to do?
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 */
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.