Skip to content

Instantly share code, notes, and snippets.

@erickgnavar
Created October 28, 2022 02:15
Show Gist options
  • Save erickgnavar/0ca8ab2252e7dbb5db634c7268d91422 to your computer and use it in GitHub Desktop.
Save erickgnavar/0ca8ab2252e7dbb5db634c7268d91422 to your computer and use it in GitHub Desktop.
function svg2png(svgContent, width, height, callback) {
// svgContent should be in base64
let svgData = svgContent;
let canvas = document.createElement("canvas");
let context = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
let image = new Image();
image.onload = function () {
// clear canvas
context.clearRect(0, 0, width, height);
// draw image with SVG data to canvas
context.drawImage(image, 0, 0, width, height);
// snapshot canvas as png
let pngData = canvas.toDataURL("image/png");
// pass png data URL to callback
callback(pngData);
};
// start loading SVG data into in memory image
image.src = svgData;
}
function downloadSVG(event, id) {
let image = document.getElementById(id);
svg2png(image.getAttribute("src"), 300, 300, function (data) {
let a = document.createElement("a");
a.download = `${image.dataset.uid}.png`;
a.href = data;
a.click();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment