Skip to content

Instantly share code, notes, and snippets.

@mugendi
Created May 19, 2024 21:51
Show Gist options
  • Save mugendi/f6af58168d0d60aad6492e42a8d84698 to your computer and use it in GitHub Desktop.
Save mugendi/f6af58168d0d60aad6492e42a8d84698 to your computer and use it in GitHub Desktop.
Replace SVG Image with PNG
function svgToPNG(svg) {
return new Promise((resolve, reject) => {
let img = document.createElement("img");
let finalImg = document.createElement("img");
let svgSize = svg.getBoundingClientRect();
let canvas = document.createElement("canvas");
canvas.width = svgSize.width;
canvas.height = svgSize.height;
let ctx = canvas.getContext("2d");
// when final image is ready
finalImg.onload = function () {
// replace svg image
svg.replaceWith(finalImg);
// resolve promise
resolve(finalImg);
};
img.onload = function () {
// now draw image to scale in canvas
ctx.drawImage(img, 0, 0, svgSize.width, svgSize.height);
// convert to data url
let imageData = canvas.toDataURL("image/png");
// set src attribute
finalImg.setAttribute("src", imageData);
};
// now start the processing
let svgData = new XMLSerializer().serializeToString(svg);
img.setAttribute("src", "data:image/svg+xml;base64," + btoa(svgData));
// ensure image is scaled to size
img.setAttribute("width", svgSize.width);
img.setAttribute("height", svgSize.height);
});
}
// To use...
let svg = document.querySelector("svg");
await svgToPNG(svg);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment