Skip to content

Instantly share code, notes, and snippets.

@cheshirecode
Last active May 24, 2022 11:48
Show Gist options
  • Save cheshirecode/29e259f4134d4a92136a473e7a364a15 to your computer and use it in GitHub Desktop.
Save cheshirecode/29e259f4134d4a92136a473e7a364a15 to your computer and use it in GitHub Desktop.
convert SVG element to PNG and download it
//takes an SVG element, draws it on a new canvas element, convert to dataURI type PNG and download it through clicking on <a>
//based on
//https://gist.github.com/mbostock/6466603
//https://gist.github.com/gustavohenke/9073132
//http://bl.ocks.org/biovisualize/8187844
export default (svg) => {
const svgData = new XMLSerializer().serializeToString( svg );
const svgSizes = svg.getBoundingClientRect();
const canvas = document.createElement("canvas")
canvas.height = svgSizes.height;
canvas.width = svgSizes.width;
const img = document.createElement( "img" );
img.onload = function() {
canvas.getContext( "2d" ).drawImage(img, 0, 0);
const a = document.createElement("a");
a.download = "fallback.png";
a.href = canvas.toDataURL("image/png");
a.click();
};
img.setAttribute( "src", "data:image/svg+xml;base64," + btoa( svgData ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment