Creating an image from an svg is not working

Tags: , , , ,



I have been trying to create an image (using the window.Image class) out of an DataURL. This DataURL contains a svg tag and a foreignObject. But it just stays completely empty. I also tried to draw this image on a canvas, but I don’t think that’s the problem since I can’t even get a correctly looking image.

Finished DataURL

data:image/svg+xml;charset=utf8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22200%22%20height%3D%22200%22%3E%3CforeignObject%20width%3D%22100%25%22%20height%3D%22100%25%22%3E%3Cdiv%20style%3D%22background-color%3Ared%22%3Etest%3C%2Fdiv%3E%3C%2FforeignObject%3E%3C%2Fsvg%3E

The templated SVG tag

NOTE: A ReactJS Component (<Component />) is being parsed to a string. But it does not contain any styles, it’s just a simple div with some text in it.

const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><foreignObject width="100%" height="100%">${renderToStaticMarkup(
        <Component />
    )}</foreignObject></svg>`;

The templated DataURL

const url = `data:image/svg+xml;charset=utf8,${encodeURIComponent(svg)}`;

Loading of the Image

const image = new window.Image(url);
image.src = url;

Image to Canvas

const ctx = canvas.getContext("2d");
const image = await loadImage(url) // a simple wrapper function which waits for the image to load that returns a promise
ctx.drawImage(image, 0, 0);

Answer

If you open the finished URL you can see that there is no red background object, I think because the div element is not rendered or not even present.

Try to set xmlns attribute in div element to http://www.w3.org/1999/xhtml, like this:

data:image/svg+xml;charset=utf8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22200%22%20height%3D%22200%22%3E%3CforeignObject%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20x%3D%220%22%20y%3D%220%22%20width%3D%22200%22%20height%3D%22200%22%3E%0A%3Cdiv%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxhtml%22%20style%3D%22background-color%3A%20red%22%3Etest%3C%2Fdiv%3E%0A%20%20%20%20%3C%2FforeignObject%3E%3C%2Fsvg%3E

example:

<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
    <foreignObject x="0" y="0" width="200" height="200">
        <div xmlns="http://www.w3.org/1999/xhtml" style="background-color: red">test</div>
    </foreignObject>
</svg>

Reference:

ForeignObject: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject



Source: stackoverflow