Note that there are some explanatory texts on larger screens.

plurals
  1. PODynamically modifying an SVG filter with javascript
    text
    copied!<p>I'm trying to create a dynamic blur effect, that can be modified with javascript on the fly.</p> <p>To start with, I'm using this really simple svg filter:</p> <pre><code>&lt;svg version="1.1" xmlns="http://www.w3.org/2000/svg"&gt; &lt;filter id="blur"&gt; &lt;feGaussianBlur stdDeviation="0" /&gt; &lt;/filter&gt; &lt;/svg&gt; </code></pre> <p>The stdDeviation starts at 0, and I want to be able to change that with the javascript. I've tried a few different things, but I haven't quite been able to nail it down.</p> <p>Firstly, (and I should note that I am using jQuery) I tried to simply select the feGaussianBlur element and modify it's attribute:</p> <pre><code>$('feGaussianBlur').attr('stdDeviation',5); </code></pre> <p>This didn't replace the already existing attribute like I expected, but rather, added another, leaving me with <code>&lt;feGaussianBlur stdDeviation="0" stdDeviation="5" /&gt;</code> Removing the original stdDeviation from the HTML made it so that there was only one attribute after the change, but it had no effect.</p> <p>Next, I attempted to simply replace the contents of the filter with the new one:</p> <pre><code>$('filter#blur').html('&lt;feGaussianBlur stdDeviation="5" /&gt;'); </code></pre> <p>This time, not only did it not succeed in changing, but it caused the element that this filter is applied to, to disappear completely (I assume the filter was corrupted, or somesuch).</p> <p>I even tried re-applying the css declaration for the filter afterwards, for both of the previous cases.</p> <p>The one thing that I tried that DID work, was to build out 10 different filters, with 10 different values, and then rather than changing the SVG with the javascript, I simply reassigned the css to a different filter ID. To be honest, this approach seems a little more.. proper? The big downside though is that it isn't very versatile, and takes a lot of work to change things. Also, I'd prefer to use values with a decimal place, which would require 100 filter declarations to accomplish.</p> <p>So, my question is... Is there a good way to dynamically modify an SVG filter (in my case, the blur filter specifically) using javascript? If there is, is it a respectable approach, in terms of semantics and standards? If nothing else, I'm more than willing to fall back to my solution of using a few (I can live without decimals) filters and swapping them out, but I want to explore my options first.</p> <p>Or, if you don't have a solution, but could at least explain to me why my first couple attempts did not work, please let me know! I'm curious what the reasons are.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload