32: SVG Filters on SVG and HTML Elements

(Updated on )

Perhaps you’ve heard of CSS filters? You can apply them do any element from CSS, like:

.apply-css-filter {
  -webkit-filter: grayscale(0.5);
  filter: grayscale(0.5);
}

You can even apply that to a HTML element or an SVG element.

But there is also filters you can define within SVG, and there are more options when you do. Here’s an example definition:

<svg>
  <defs>
    <filter id="pictureFilter">
      <feMorphology operator="erode" radius="2" />
    </filter>
  </defs>
</svg>

You then can apply it to an element right in the SVG like:

<svg>
  <!-- could be anything -->
  <image filter="url(#pictureFilter)" xlink:href="image.jpg" width="100%" height="100%" x="0" y="0" />
</svg>

Or, from the CSS by referencing the ID similarly:

.apply-svg-filter {
  -webkit-filter: url(#pictureFilter);
  filter: url(#pictureFilter);
}

There are a lot SVG filters. Familiar ones like blur, and weird ones that apply painterly effects. Here’s the spec.