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


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="" width="200" height="200"><foreignObject width="100%" height="100%">${renderToStaticMarkup(
        <Component />

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);


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, like this:



<svg xmlns="" width="200" height="200">
    <foreignObject x="0" y="0" width="200" height="200">
        <div xmlns="" style="background-color: red">test</div>



Source: stackoverflow