Skip to content

Instantly share code, notes, and snippets.

@speed-of-light
Last active May 23, 2018 16:08
Show Gist options
  • Save speed-of-light/82237c55acb969d608df7dd549cca4dc to your computer and use it in GitHub Desktop.
Save speed-of-light/82237c55acb969d608df7dd549cca4dc to your computer and use it in GitHub Desktop.
Get that svg as png
var png = {
selector: "#aaaa",
w: "500px", h: "500px",
fn: "fallback.png"
};
function svg2png({ selector, w, h, fn }) {
var svg = document.querySelector( selector );
var svgData = new XMLSerializer().serializeToString( svg );
var canvas = document.createElement( "canvas" );
var ctx = canvas.getContext( "2d" );
canvas.setAttribute('width', w);
canvas.setAttribute('height', h);
var img = document.createElement( "img" );
img.setAttribute( "src", "data:image/svg+xml;base64," + btoa( svgData ) );
img.onload = function() { ctx.drawImage( img, 0, 0 );
var a = document.createElement("a");
a.download = fn;
a.href = canvas.toDataURL("image/png");
a.click();
};
}
svg2png(png);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment