Skip to content
Advertisement

SVG to Image returning blank image blob

I have an interactive drawing app on my website, and I want to create a button where one could share their drawing on FB.

I’m trying to convert the SVG element to a blob, to then pass it to og:image, but I’m having some issues with the conversion.

I have two trials: one doesn’t trigger the onload function for some reason. The other returns an empty blob

both trials work fine on jsfiddle however.

First Attempt

JavaScript

Second Attempt

JavaScript

Here’s the app with the two attempts triggered by the two buttons “test1” and “test2”

Advertisement

Answer

The problem lies in the way you did define the xmlns:xlink attributes.
Currently from your page doing document.querySelector("use").attributes.getNamedItem("xmlns:xlink").namespaceURI will return null. This means that this attribute has been defined in the Document’s namespace (HTML), so when you’ll stringify it using the XMLSerializer, you will actually have two xmlns:xlink attributes on your elements, one in the HTML namespace, and the SVG one that is implied in an SVG embed in an HTML document.
It is invalid to have two same attributes on the same element in SVG, and thus your file is invalid and the image won’t load.

If you are facing this issue it’s certainly because you did set this attribute through JavaScript:

JavaScript
JavaScript

To set it correctly, you need to use setAttributeNS() and use the XMLNS namespace:

JavaScript
JavaScript

However the best is to not set at all these attributes.
As I said above, SVGs embedded in HTML do automatically have the correct xmlns and xlink namespaces defined without the need for attributes. And since you are creating your elements through JS, you already do define them in the correct namespace too.
So don’t bother with these attributes:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement