Skip to content

Instantly share code, notes, and snippets.

@mavaddat
Forked from rafaelsq/svg_to_png.js
Last active October 26, 2021 03:34
Show Gist options
  • Save mavaddat/6d0b746f578023012917ea6e0c1f110d to your computer and use it in GitHub Desktop.
Save mavaddat/6d0b746f578023012917ea6e0c1f110d to your computer and use it in GitHub Desktop.
SVG to Base64 PNG
function svgToPng(svg, callback) {
var svgContent = null;
//check if svg is a path string
if (typeof svg === 'string') {
//get svg element
var client = new XMLHttpRequest();
client.open('GET', svg);
client.onreadystatechange = function() {
svgContent = client.responseText;
}
client.send();
} else if (svg.nodeType === 1) { //checks that svg is an element
svgContent = (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");
//Encode URI component for svgContent
//Compute new string in which hexadecimal escape sequences are replaced with the character that it represents without using deprecated `btoa` or `unescape` functions
var svgContentEncoded = (encodeURIComponent(svgContent)).replace(/\%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
});
var svgBase64 = Buffer.from(svgContentEncoded, 'utf8').toString('base64');
var img = document.createElement("img");
img.setAttribute("src", "data:image/svg+xml;base64," + svgBase64);
img.onload = function() {
ctx.drawImage(img, 0, 0);
callback(canvas.toDataURL("image/png"))
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment