我在网页上嵌入了以下 SVG 图像:
const svg = document.getElementById('svg');
const filter = document.createElementNS('http://www.w3.org/2000/svg', 'filter');
filter.setAttribute('id', 'image');
filter.setAttribute('x', '0%');
filter.setAttribute('y', '0%');
filter.setAttribute('width', '100%');
filter.setAttribute('height', '100%');
const feImage = document.createElementNS('http://www.w3.org/2000/svg', 'feImage');
feImage.setAttribute('xlink:href', 'http://lorempixel.com/100/100/');
filter.appendChild(feImage);
svg.querySelector('defs').appendChild(filter);
svg.querySelector('circle').setAttribute('filter', 'url(#image)');
<svg width="200" height="200" viewBox="0 0 200 200" id="svg">
<defs></defs>
<circle cx="100" cy="100" r="50" fill="none" stroke-width="2" stroke="gray"></circle>
</svg>
现在我想动态地向这个 svg 添加一个图像过滤器,然后将过滤器应用于圆圈。但实际情况是圆圈变得不可见,过滤器不起作用。
当我将过滤器添加到硬编码的 svg 时,一切正常:
<svg width="200" height="200" viewBox="0 0 200 200" id="svg">
<defs>
<filter id="image" x="0%" y="0%" width="100%" height="100%">
<feImage xlink:href="http://lorempixel.com/100/100/"></feImage>
</filter>
</defs>
<circle cx="100" cy="100" r="50" fill="none" stroke-width="2" stroke="gray" filter="url(#image)"></circle>
</svg>
我的问题是为什么这行不通?
最佳答案
您需要使用: document.createElementNS(…) 用于 svg 元素,在本例中为 setAttributeNS(…) 还有;
例如改变:
const filter = document.createElement('filter');
到
const filter = document.createElementNS('http://www.w3.org/2000/svg', 'filter');
另外改变:
feImage.setAttribute('xlink:href', 'http://lorempixel.com/100/100/');
到
feImage.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'http://lorempixel.com/100/100/');
关于javascript - 动态添加过滤器到 SVG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55160083/