How can I add a filter to a SVG object in JavaScript?

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

I am trying 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);

Answers:

Answer

The above code works for me now! One can simply use the createElementNS, setAttribute and appendChild methods.

Answer

If you prefer more readable code - like I do - svg.js now has a svg filter plugin. Your example code would reduced to:

var draw = SVG('canvas')

draw.rect(90,90)

rect.filter(function(add) {
  add.gaussianBlur('15')
})

It is probably a year too late but still worth mentioning :)

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.