我有一个 <svg>
元素(带有 viewBox
集),我附加了一个以编程方式构造的 <image>
元素,像这样:
const img=document.createElementNS('http://www.w3.org/2000/svg','image');
img.setAttribute('width','100');
img.setAttribute('height','100');
img.setAttribute('xlink:href','data:image/png;base64,iVBORw0KGgoAAA'+
'ANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4'+
'//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU'+
'5ErkJggg==');
document.querySelector('svg').appendChild(img);
它出现在 SVG 中,但没有显示任何内容。然而,当我调用 img.outerHTML = img.outerHTML;
从它的文本表示中重新创建它,它开始正确显示。
任何人都可以帮助我了解发生了什么?我应该如何在 JS 中创建元素以使其正常显示?
最佳答案
对于支持 SVG-2 的浏览器,您可以简单地执行 setAttribute("href", url)
。
但是,在 SVG-1.x 中,您必须使用 setAttributeNS('http://www.w3.org/1999/xlink', 'href', url);
实际上对于setAttributeNS
,您还可以使用'xlink:href'
作为第二个参数或'foo:href'
,因为setAttributeNS
负责映射到正确的 NameSpace 并丢弃 :
之前的内容,但 setAttribute
不会,因此创建了一种 null:xlink:href
属性,它不映射到浏览器已知的任何内容,因此失败。
const url = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
const img = document.createElementNS('http://www.w3.org/2000/svg','image');
img.setAttribute('width','100');
img.setAttribute('height','100');
img.setAttribute('href', url); // SVG-2
img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', url); // SVG-1.x
document.querySelector('svg').appendChild(img);
<svg viewBox="0 0 100 100"></svg>
关于javascript - 在 JS 中创建的 SVG <image> 元素不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57154530/