Skip to content

Instantly share code, notes, and snippets.

@rafaelsq
Created February 18, 2020 11:49
Show Gist options
  • Save rafaelsq/665c48fb0fc58434b4e13b70717386cc to your computer and use it in GitHub Desktop.
Save rafaelsq/665c48fb0fc58434b4e13b70717386cc to your computer and use it in GitHub Desktop.
SVG to PNG
function svg_to_png(svg, callback) {
var svgData = (new XMLSerializer()).serializeToString(svg);
var canvas = document.createElement("canvas");
var svgSize = svg.getBoundingClientRect();
canvas.width = svgSize.width;
canvas.height = svgSize.height;
var ctx = canvas.getContext("2d");
var img = document.createElement("img");
img.setAttribute("src", "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(svgData))) );
img.onload = function() {
ctx.drawImage(img, 0, 0);
callback(canvas.toDataURL("image/png"))
};
}
@rafaelsq
Copy link
Author

svg_to_png($0, console.log)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment