【问题标题】:how to append a <svg> element with vanilla JavaScript?如何使用原生 JavaScript 附加 <svg> 元素?
【发布时间】:2020-03-21 23:40:09
【问题描述】:

以下原版 Javascript 代码附加了一个 &lt;svg&gt; 和一个 &lt;style&gt; 元素

var text="";
text=text+"<defs>"
text=text+"<filter id='Matrix' filterUnits='objectBoundingBox' x='0%' y='0%' width='100%' height='100%'>"
text=text+"<feColorMatrix type='matrix' in='SourceGraphic' values='0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0'/>"
text=text+"</filter>"
text=text+"</defs>"

var tag;
tag = document.createElement("svg");
document.body.appendChild(tag);
tag.innerHTML=text;
tag = document.createElement("style");
document.body.appendChild(tag);
tag.innerHTML="img.free {filter:url('#Matrix')}";

在以下 html 代码中从图像中删除红色:

<head>
</head>
<body>
<img class="free" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/500px-Google_2015_logo.svg.png">
</body>

(jsfiddle here)

但是,&lt;svg&gt; 元素内的过滤器未应用。

请注意页面的静态版本(jsfiddle here)没有这样的问题。

如何通过 Javascript 注入 &lt;svg&gt; 元素并使过滤器正常工作?

【问题讨论】:

标签: javascript html svg


【解决方案1】:

SVG 元素必须在 SVG 命名空间中创建。

var text="";
text=text+"<defs>"
text=text+"<filter id='Matrix' filterUnits='objectBoundingBox' x='0%' y='0%' width='100%' height='100%'>"
text=text+"<feColorMatrix type='matrix' in='SourceGraphic' values='0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0'/>"
text=text+"</filter>"
text=text+"</defs>"

var tag;
tag = document.createElementNS("http://www.w3.org/2000/svg", "svg");
document.body.appendChild(tag);
tag.innerHTML=text;
tag = document.createElementNS("http://www.w3.org/2000/svg", "style");
document.body.appendChild(tag);
tag.innerHTML="img.free {filter:url('#Matrix')}";
<head>
</head>

<body>
  <img class="free" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/500px-Google_2015_logo.svg.png">
</body>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 2012-01-11
    • 1970-01-01
    • 2018-07-15
    • 2011-02-14
    • 2020-01-01
    • 2016-09-30
    相关资源
    最近更新 更多