How to add a filter to an SVG object in JavaScript?

I am trying to create and add a feGaussianBlur filter to an SVG rectangle using JavaScript using this code as a link. I get a rectangle, but it is not filtered. What am I doing wrong?

I try like this:

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); 
+7
source share
2 answers

This code works for me now! You can simply use the createElementNS , setAttribute and appendChild .

+4
source

If you prefer a more readable code - like me, svg.js now has an svg filter plugin . Your sample code will decrease to:

 var draw = SVG('canvas') draw.rect(90,90) rect.filter(function(add) { add.gaussianBlur('15') }) 

It may already be too late, but worth mentioning :)

0
source

All Articles