SVG filters and effects

Filters in SVG are usually created inside the <defs> element and given an ID for referencing later, this can be as an attribute on an SVG element or defined in CSS.

Filters in SVG are powerful and can be used to produce some truly stunning effects! In order to use a filter in SVG we use the <filter> element. Inside of this element we have a number of tools available to us; Blend, Colour Matrix, Component Transfer, Composite, Convolve Matrix, Diffuse Lighting, Displacement Map, Flood, Gaussian Blur, Image, Merge, Morphology, Offset, Specular Lighting, Tile and Turbulence. These are called filter primitives. An SVG filter is made up using a number of these filter primitives.

A filter primitive has one or two inputs and one output. For the input we have a number of options available to us to due to browser support the main two are:

SourceAlpha Only the opaque parts of the alpha channel from the source graphic (essentially the element but filled black without any styles).

We'll take a look at a few of the filter primitives available to us below and cover basic usage. Filters in SVG can be complicated, we'll only be covering the basics.

Blur

The blur filter primitive can be used to apply blurring to an element. The filter primitive is created using the <feGaussianBlur> element and the amount of blurring is controlled using the stdDeviation attribute.

<feGaussianBlur stdDeviation="25" />

Offset

The offset filter primitive can be used to position elements at an offset of their source. The filter primitive is created using the <feOffset> element and controlled using the dx and dy attributes. These attributes specify the x and y amounts of the offset. This filter is often combined with blurring to create a drop shadow.

<feOffset dx="15" dy="15" />

Colour Matrix

The colour matrix filter primitive can be used to perform a number of colour transformations. The filter primitive is created using the <feColorMatrix> element and controlled using the type and values attributes.

<feColorMatrix type="hueRotate" values="171" />

Turbulence

The turbulence filter primitive can be used to generate noise and artificial textures. The filter primitive is created using the <feTurbulence> element and controlled using a number of attributes.

Morphology

The morphology filter primitive can be used to erode or dilate an element. The filter primitive is created using the <feMorphology> elements and is controlled using the operator and radius attributes. This filter is often used for thinning or flattening.

06. Apply pattern to the moon

Now we've created the filter and applied it to our pattern, the only thing left to do is apply it to our chosen element. In this case we'll apply it using CSS but we could just as easily apply the filter inline.