Code and Stuff

Dec 24, 2012

CSS3 SVG Filters (1)

CSS3 Filters (not to be confused with the, now deprecated, Microsoft CSS filters) are used to post-process the rendering of parts of the DOM. They are still a Draft and might change in the future. However, firefox and webkit have already some implementations.

Filters are enabled on one or more DOM elements with the CSS property filter. There are two quite different ways to implement filters. The more immediate one is by adding one or more filter directly in the CSS. The other is by specifying an URL to a SVG filter. This latter way is much more flexible and feature rich. It requires, however, that the browser supports SVG. Fortunately all major ones do so.

Example/Generator

In this example only some SVG filters are shown.

FilterRange
Blur: Positive value (pixels)
Saturation: Between 0 and 1
Brightness: Positive
Sepia: Positive
Hue Rotation: Any number of degrees

CSS

#element {
  filter: url(#myfilter);
  -webkit-filter: url(#myfilter);
}

HTML

Somehwere in the HTML code we have to place this SVG tag. Since it's size is 0x0 it should not affect the rendering of the page. The only child of this SVG is the filter we set in the CSS (myfilter).
<svg width="0" height="0" xmlns="http://www.w3.org/2000/svg">
  <filter id="myfilter">
    <!-- Blur -->
    <feGaussianBlur in="SourceGraphic" stdDeviation="1"/>
    
    <!-- Saturation -->
    <feColorMatrix type="saturate" values="1"/>
    
    <!-- Brightness -->
    <feComponentTransfer>
      <feFuncR type="linear" slope="1"/>
      <feFuncG type="linear" slope="1"/>
      <feFuncB type="linear" slope="1"/>
    </feComponentTransfer>

    <!-- Sepia (with color matrix:
    (0.393+0.607*[1-0]) (0.769-0.769*[1-0]) (0.189-0.189*[1-0]) 0 0
    (0.349-0.349*[1-0]) (0.686+0.314*[1-0]) (0.168-0.168*[1-0]) 0 0
    (0.272-0.272*[1-0]) (0.534-0.534*[1-0]) (0.131+0.869*[1-0]) 0 0
    0 0 0 1 0
    -->
    <feColorMatrix type="matrix"
               values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0"/>
    
    <!-- Hue Rotation -->
    <feColorMatrix type="hueRotate" values=" 0"/>
  </filter>
</svg>

Chrome Problems

While implementing the scripts of this post I encountered a problem with chrome. When changing some of the filters by modifying the DOM with javascript the image was not updated. I noticed however that when the blur was changed, the filter was applied. A quick workaround was, therefore, to change the blur and set it back at each value change.

A probably better solution to the problem is to remove and re-add the filter.