javascript - 动态添加过滤器到 SVG

标签 javascript html svg

我在网页上嵌入了以下 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/');

fiddle

关于javascript - 动态添加过滤器到 SVG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55160083/

相关文章:

javascript - 设置 td 检查属性

javascript - 为什么我们必须在 es6 箭头函数中用括号包裹 throw

javascript - 如何使用 Snap.svg 和 Angular 5 在悬停时缩放不同的 svg 图层

javascript - 如何使用 React Native 创建模态窗口?

javascript - 具有 "asc"和 "desc"的多列排序的数据表

Javascript 贪吃蛇游戏错误

html - 你能在保持相同高度的同时拉伸(stretch)字体大小吗?

html - 更改 Bootstrap 3 导航菜单中的布局间距

css 不改变 svg 填充不透明度

vue.js - 在 Vue 组件中将样式元素添加到 SVG