JavaScript Answers

How to Convert inline SVG to Base64 string with JavaScript?

Spread the love

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" />

Then we write:

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

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:


logged as a result.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.