Categories
JavaScript Answers

How to convert inline SVG to Base64 string with JavaScript?

Spread the love

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.

How to convert inline SVG to Base64 string with JavaScript?

To convert inline SVG to Base64 string with JavaScript, we use the serializeToString method.

For instance, we write

const s = new XMLSerializer().serializeToString(document.getElementById("svg"));
const encodedData = window.btoa(s);

to call serializeToString with the svg element we get from getElementById to convert it to an svg string.

Then we call btoa with s to convert it to a base64 URL string.

Conclusion

To convert inline SVG to Base64 string with JavaScript, we use the serializeToString method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *