-
-
Save mavaddat/6d0b746f578023012917ea6e0c1f110d to your computer and use it in GitHub Desktop.
SVG to Base64 PNG
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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