如何在JavaScript中向SVG对象添加过滤器?

sto*_*p64 7 javascript svg svg-filters

我正在尝试使用JavaScript创建并添加feGaussianBlur过滤器到SVG矩形,使用此代码作为参考.我得到一个矩形,但它没有过滤.我究竟做错了什么?

我这样想:

var container = document.getElementById("svgContainer");
var mySvg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
mySvg.setAttribute("version", "1.1");
container.appendChild(mySvg);

var obj = document.createElementNS("http://www.w3.org/2000/svg", "rect");
obj.setAttribute("width", "90");
obj.setAttribute("height", "90");

var defs = document.createElementNS("http://www.w3.org/2000/svg", "defs");

var filter = document.createElementNS("http://www.w3.org/2000/svg", "filter");
filter.setAttribute("id","f1");
filter.setAttribute("x","0");
filter.setAttribute("y","0");

var gaussianFilter = document.createElementNS("http://www.w3.org/2000/svg", "feGaussianBlur");
gaussianFilter.setAttribute("in","SourceGraphic");
gaussianFilter.setAttribute("stdDeviation","15");

filter.appendChild(gaussianFilter);
defs.appendChild(filter);
mySvg.appendChild(defs);    
obj.setAttribute("filter","url(#f1)");

mySvg.appendChild(obj);
Run Code Online (Sandbox Code Playgroud)

sto*_*p64 5

上面的代码现在对我有用!可以简单地使用createElementNS,setAttributeappendChild方法。

  • 谢谢你回来回答 (2认同)