繁体   English   中英

如何附加一个<svg>元素与香草 JavaScript?

[英]how to append a <svg> element with vanilla JavaScript?

以下 vanilla Javascript 代码附加了一个<svg>和一个<style>元素

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在这里

但是, <svg>元素内的过滤器并未应用。

请注意,页面的静态版本(此处为jsfiddle)没有此类问题。

如何通过 Javascript 注入<svg>元素并使过滤器工作?

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM