Skip to content

Instantly share code, notes, and snippets.

@rafaelsq
Last active October 25, 2021 22:02
Show Gist options
  • Save rafaelsq/a9426f765d09e09b62f5dca67c3cb68d to your computer and use it in GitHub Desktop.
Save rafaelsq/a9426f765d09e09b62f5dca67c3cb68d to your computer and use it in GitHub Desktop.
SVG to Base64 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

// Usage
svg_to_png(document.getElementById("svg"), console.log)

@rafaelsq
Copy link
Author

rafaelsq commented Jan 6, 2020

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