Although usually, we shouldn't rely on this kind of logic for production stuff, because there's always a better alternative to prevent you from doing this, sometimes this doesn't depend on you but on third party stuff. Whether you are scrapping content from the web or creating an automatization script that modifies some vectorized image, knowing this simple trick of how to convert a rendered SVG node in the browser to a picture in base64 format doesn't harm you.
Consider the following example of a SVG element rendered in the DOM of the browser, this element has an id that makes it part of the dom, namely mySvgElement
:
Rendered in the browser it will display a picture like this:
In order to convert this element to its base64 representation, we would simply need the DOM element and the help of the XMLSerializer class. The XMLSerializer interface provides the serializeToString() method to construct an XML string representing a DOM tree. In our case, with the mentioned element we would just do:
Note that the serialized string generated by the XMLSerializer will return the plain SVG, so encoded into base64, we would obtain the plain base64 data:
If you want to display it in the browser using the Data URL representation, you would need to add as prefix to the generated data "data:image/svg+xml;base64,":
Which should produce now:
Happy coding !
Comments
Post a Comment