我正在尝试构建以下 SVG:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="render" height="200px" width="100%" viewBox="0 0 100 50">
<image x="0" y="-25" width="100" height="50" xlink:href="https://environmentaldashboard.org/cv_slides/categorybars/nature_photos.png"></image>
</svg>
当 <image>
静态地是 SVG 的一部分,它加载得很好。但是,使用 JavaScript 动态加载图像不起作用:
var image = makeSVG('image', {
x: 0,
y: -25,
width: 100,
height: 50,
'xlink:href': 'https://environmentaldashboard.org/cv_slides/categorybars/nature_photos.png'
});
document.getElementById('render').appendChild(image);
var circle = makeSVG('circle', {
cx: 100,
cy: 50,
r: 40,
stroke: 'black',
'stroke-width': 2,
fill: 'red'
});
document.getElementById('render').appendChild(circle);
function makeSVG(tag, attrs) { // https://stackoverflow.com/a/3642265/2624391
var el = document.createElementNS('http://www.w3.org/2000/svg', tag);
for (var k in attrs) {
el.setAttribute(k, attrs[k]);
}
return el;
}
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="render" height="200px" width="100%" viewBox="0 0 100 50"></svg>
可以肯定的是makeSVG()
功能正在工作我还附加了 <circle>
这是正确渲染的。为什么我无法加载<image>
一样的方法?当我在浏览器中检查元素时,我可以看到该元素突出显示,但是它是空白的。
最佳答案
使用setAttributeNS方法添加命名空间相关属性xlink
for (var k in attrs) {
if (k == 'xlink:href') {
el.setAttributeNS("http://www.w3.org/1999/xlink", 'xlink:href', attrs[k]);
} else {
el.setAttribute(k, attrs[k]);
}
}
关于javascript - 动态加载的 <image> 未在 SVG 中渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50950641/