Generated SVG image doesn't display

2020-04-28 09:22发布

问题:

I'm developing a JavaScript class to show all SVG objects, but when I create the element "image", the browser doesn't display it. Though if I copy the generated code and put it in another document, the image is displayed.

When I searched the image using Firebug's inspector, the object appears but the image is not displayed.

I created the object using appendChild(), setAttribute() and setAttributeNS()

This is the generated code:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="100%" width="100%" >
<image width="50" height="50" xlink:href="logo.png" y="20" x="20" id="d"></image>
</svg>

What I am doing wrong?

回答1:

The problem were the namespaces. This is the correct form to create images dynamically:

image.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'flower.png');

More imformation can be found on MDN's 'Namespaces Crash Course'.