Sometimes, we want to convert inline SVG to base64 string with JavaScript.
In this article, we’ll look at how to convert inline SVG to base64 string with JavaScript.
Convert inline SVG to Base64 string with JavaScript
To convert inline SVG to base64 string with JavaScript, we can use the serializeToString method available with a XMLSerializer instance to parse the svg element to an XML string.
Then we call window.btoa to convert the string into a base64 string.
For instance, if we have:
<svg height="100" width="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>
Then we write:
const s = new XMLSerializer().serializeToString(document.querySelector("svg"))
const encodedData = window.btoa(s);
console.log(encodedData)
We call serializeToString with the svg element object that’s returned with document.querySelector.
Then we call window.btoa on the string returned by serializeToString.
Therefore, from the console log, we get:
PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTAwIiB3aWR0aD0iMTAwIj4KICA8Y2lyY2xlIGN4PSI1MCIgY3k9IjUwIiByPSI0MCIgc3Ryb2tlPSJibGFjayIgc3Ryb2tlLXdpZHRoPSIzIiBmaWxsPSJyZWQiLz4KPC9zdmc+
logged as a result.
Conclusion
To convert inline SVG to base64 string with JavaScript, we can use the serializeToString method available with a XMLSerializer instance to parse the svg element to an XML string.
Then we call window.btoa to convert the string into a base64 string.