tic*_*tic 1 html javascript svg
以下普通 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')}";
Run Code Online (Sandbox Code Playgroud)
使用以下 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>
Run Code Online (Sandbox Code Playgroud)
(这里是jsfiddle )
然而,元件内部的过滤器<svg>不适用。
请注意,页面的静态版本(此处为jsfiddle )不存在此类问题。
如何<svg>通过 Javascript 注入元素并使过滤器正常工作?
SVG elements must be created in the SVG namespace.
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')}";Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)