Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically injecting SVG filters and applying to HTML

I'm playing around with applying SVG filters to HTML. This works if everything's hard coded, although I need the -webkit-filter CSS id for chrome. When attempting to create an SVG element with a filter dynamically with javascript it fails. Can anyone explain why?

Here's what I have so far: http://jsfiddle.net/H3UX8/1/

The first image and text pair are blurred on chrome and firefox but the second pair are not.

The extract doesn't work:

.dynamic div {
    -webkit-filter: url('#f2');
    filter: url('#f2');
}

...

var svg = document.createElement("svg");
var filter = document.createElement("filter");
filter.setAttribute("id", "f2");
var blur = document.createElementNS("http://www.w3.org/2000/svg", "feGaussianBlur");
blur.setAttribute("stdDeviation", "5");
filter.appendChild(blur);
svg.appendChild(filter);
document.body.appendChild(svg);

...

<div class="dynamic">
    <div><img src="http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png" /></div>
    <div>HELLO WORLD TWO</div>
</div>

The html syntax looks identical. I'm guessing either document.createElement doesn't create svg capable tags or maybe the filter IDs are only read once on document load. I can, however, dynamically change the value of stdDeviation in the static example.

like image 260
jozxyqk Avatar asked Dec 02 '13 07:12

jozxyqk


1 Answers

Try this:

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

var filter = document.createElementNS( NS, "filter" );
filter.setAttribute( "id", "f2" );

var blur = document.createElementNS( NS, "feGaussianBlur" );
blur.setAttribute( "stdDeviation", "5" );

filter.appendChild( blur );
svg.appendChild( filter );
document.body.appendChild( svg );
like image 179
sbking Avatar answered Oct 17 '22 13:10

sbking