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);
Modern browsers support using SVG within CSS styles to apply graphical effects to HTML content. You may specify SVG in styles either within the same document or an external style sheet. There are 3 properties you can use: mask , clip-path , and filter .
Like CSS rules, an SVG filter can be a set of directives to add another visual layer on top of conventional text. With the CSS filter property, these effects can be used outside of SVG and be applied directly to HTML content.
<filter> The <filter> SVG element defines a custom filter effect by grouping atomic filter primitives. It is never rendered itself, but must be used by the filter attribute on SVG elements, or the filter CSS property for SVG/HTML elements.
The above code works for me now! One can simply use the createElementNS
, setAttribute
and appendChild
methods.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With