Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 446
stonecup64 Avatar asked Jun 03 '12 01:06

stonecup64


People also ask

Can I use SVG filter?

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 .

How do SVG filters work?

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.

What is filters in SVG path Path filter element Canva circle tag?

<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.


2 Answers

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

like image 125
stonecup64 Avatar answered Sep 20 '22 03:09

stonecup64


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 :)

like image 37
wout Avatar answered Sep 21 '22 03:09

wout