Filter

Filters are SVG's mechanism to create sophisticated effects.

Filters are defined by the <filter> element, which should be put in the <defs> section of your SVG, and you must give the filter an id so you can reference it elsewhere. (You would reference the filter using the filter attribute.)

How filter primitive works

Between the <filter> tags, goes a list of primitives (the <fe*> tags). Primitives are basic operations like blurring, adding a lighting effect, etc.

They take in images specified by the in and/or in2 attributes, and store the result in a name specified by the result attribute.

Primitive global attributes

All primitives accept these attributes:

  • result name for the filter primitive result; the name can be referenced in the in or in2 attribute of another primitive.
  • x, y, width, height position and dimension of the filter primitive viewport (to "crop out" the filter primitive layer)

Primitive in and in2 attributes

For in or in2, you can specify one of the following:*

  • SourceGraphic use the graphic elements that use the <filter>
  • SourceAlpha use the graphic elements that use the <filter>, but only use the alpha channel (the colors will become gray)
  • The name from a result attribute

The default value is SourceGraphic for first filter primitive, otherwise it's the result of the previous filter primitive.

Illustration of different in values. The image consists a group of 3 RGB circles on top of a vertical rectangle. The blur filter effect is applied on the group of RGB circles.
Illustration of different in values. The image consists a group of 3 RGB circles on top of a vertical rectangle. The blur filter effect is applied on the group of RGB circles. (Source: W3)

(*) I omit BackgroundImage, BackgroundAlpha, FillPaint, and StrokePaint as I don't understand what the spec is saying, and it's not consistent on Chrome and Firefox. (See the in attribute test)

Filter SVG element

<filter>

  • x x coordinate offset of the filter
  • y y coordinate offset of the filter
  • width width the filter
  • height height of the filter
  • filterUnits defines the coordinate system for attributes x, y, width, height; specify userSpaceOnUse (use viewport/absolute coordinate) or objectBoundingBox (use the bounding box of the element that references the filter, with coordinate values ranging from 0 to 1)
  • primitiveUnits defines the coordinate system for the filter primitives (the children of <filter>); specify userSpaceOnUse (use viewport/absolute coordinate) or objectBoundingBox (use the bounding box of the element that references the filter, with coordinate values ranging from 0 to 1)
| LIVE PREVIEW

Primitive SVG elements

In addition to the attributes mentioned below, all primitives also accept the following "global" attributes: result, x, y, width, height.

<feBlend>

Composes objects together and apply a blending mode.

  • in first input (the "top" image)
  • in2 second input (the "bottom" image)
  • mode the blending mode to use; specify: normal, darken, lighten, multiply, screen, overlay, color-dodge, color-burn, hard-light, soft-light, difference, exclusion, hue, saturation, color, or luminosity
| LIVE PREVIEW

<feColorMatrix>

Changes colors based on a transformation matrix. (The final RGBA value will be clamped between 0 and 1.)

[rgba1]=[r1r2r3r4r5g1g2g3g4g5b1b2b3b4b5a1a2a3a4a500001][rgba1] \begin{bmatrix} r' \\ g' \\ b' \\ a' \\ 1 \\ \end{bmatrix} = \begin{bmatrix} r_1 & r_2 & r_3 & r_4 & r_5 \\ g_1 & g_2 & g_3 & g_4 & g_5 \\ b_1 & b_2 & b_3 & b_4 & b_5 \\ a_1 & a_2 & a_3 & a_4 & a_5 \\ 0 & 0 & 0 & 0 & 1 \\ \end{bmatrix}\begin{bmatrix} r \\ g \\ b \\ a \\ 1 \\ \end{bmatrix}
  • in the input image
  • type matrix, saturate, hueRotate, or luminanceToAlpha
  • values depends on type (if you specify type other than matrix, it will construct the matrix based on the value of type and values):
    • for type="matrix": input the first four rows of the matrix (ignore the last row because it's a constant)
    • for type="saturate": input a single real number from 0 to 1
    • for type="hueRotate": input a single real number (representing the degrees)
    • for type="luminanceToAlpha": values is not required
| LIVE PREVIEW

<feComponentTransfer>

Performs remapping for each color component. It allows operations like brightness adjustment, contrast adjustment, color balance, or thresholding (MDN).

  • in the input image

<feComponentTransfer> expects you to provide these "transfer function" children elements: <feFuncR>, <feFuncG>, <feFuncB>, <feFuncA>. Each transfer function element accepts:

  • type defines how to map each color component cc to cc'. specify one of:
    • identity c=cc' = c
    • table use linear interpolation using values given in tableValues. tableValues contains n+1n+1 values (each ranging from 0 to 1), specifying the "start" and "end" values for nn evenly sized interpolation regions. A color cc would fall into one of these interpolation regions; you would then perform a linear interpolation using the "start" and "end" values of the region.
    • discrete use the step function using values given in tableValues. tableValues contains nn values (each ranging from 0 to 1), specifying a step function consisting of nn evenly sized steps. A color cc would fall into one of these "steps", you just use the tableValues value representing the step.
    • linear expects you to give slope and intercept attributes, representing mm and bb respectively. Then, c=mc+bc' = mc + b.
    • gamma expects you to give amplitude, exponent, and offset attributes, representing AA, xx, and bb respectively. Then, c=acx+bc' = ac^x + b.
| LIVE PREVIEW

<feComposite>

Performs PorterDuff compositing operations.

  • in first input (the "top" image)
  • in2 second input (the "bottom" image)
  • operator over, in, out, atop, xor, lighter or arithmetic (default is over)
  • k1, k2, k3, k4 required when operator="arithmetic". With i1i_1 and i2i_2 representing pixel channel values of in and in2 respectively, the result pixel channel value is given as r=k1(i1i2)+k2(i1)+k3(i2)+k4r = k_1 (i_1 \cdot i_2) + k_2(i_1) + k_3(i_2) + k_4
Illustration of different operator values
Illustration of different operator values (Source: Codepen)

<feConvolveMatrix>

Applies a matrix convolution filter effect. Operations that can be achieved through convolution include blurring, edge detection, sharpening, embossing and beveling (MDN).

A convolution combines pixels in the input image with its neighboring pixels to produce a resulting image. The convolution matrix ω\omega (the "convolution kernel") is an orderY (oyo_y) by orderX (oxo_x) matrix; together with divisor dd, bias bb, targetX txt_x, targetY tyt_y, yield the calculation:

cx,y=1d{i=0oy1j=0ox1c(xtx+j),(yti+i)ω(oxj1),(oyi1)}+bαx,y c'_{x,y} = \frac{1}{d} \left\{ \sum_{i=0}^{o_y-1} \sum_{j=0}^{o_x-1} c_{(x-t_x+j),(y-t_i+i)} \cdot \omega_{(o_x-j-1),(o_y-i-1)} \right\} + b \cdot \alpha_{x,y}
  • in the input image
  • order size of the kernel matrix (default is 3); if you specify two numbers (e.g. 3 4), the first number represents orderX (number of columns), and the second number respresents orderY (number or rows)
  • kernelMatrix space-separated list of numbers, representing the kernel matrix
  • divisor represents dd in the equation above (default is sum of all values inside the kernelMatrix)
  • bias represents bb in the equation above (default is 0)
  • targetX offsets the x positioning of the kernel matrix relative to the target pixel (default is centered around the target pixel, i.e. tx=ox/2t_x = \lfloor o_x / 2 \rfloor)
  • targetY offsets the y positioning of the kernel matrix relative to the target pixel (default is centered around the target pixel, i.e. ty=oy/2t_y = \lfloor o_y / 2 \rfloor)
  • edgeMode how to handle the case near the edge of the input image; specify duplicate (default), wrap, or none
  • preserveAlpha a value of false (default) indicates that the convolution will apply to all channels (including alpha channel)
| LIVE PREVIEW

<feDiffuseLighting>

Lights an image using the alpha channel as a bump map. (Bump mapping is a "texture mapping technique in computer graphics for simulating bumps and wrinkles on the surface of an object," Wikipedia.)

  • in the input image
  • surfaceScale height of surface for an alpha value of 1
  • diffuseConstant kdk_d (diffuse reflection constant) in Phong reflection model
  • lighting-color color of the light

<feDiffuseLighting> expects you to provide the light sources using <fePointLight>, <feDistantLight>, or <feSpotLight> children elements.

| LIVE PREVIEW
No Light fePointLight feDistantLight feSpotLight

<feSpecularLighting>

Lights an image using the alpha channel as a bump map. (Bump mapping is a "texture mapping technique in computer graphics for simulating bumps and wrinkles on the surface of an object," Wikipedia.)

  • in the input image
  • surfaceScale height of surface for an alpha value of 1
  • specularConstant ksk_s (specular reflection constant) in Phong reflection model
  • specularExponent larger value means more "shiny"
  • lighting-color color of the light

<feDiffuseLighting> expects you to provide the light sources using <fePointLight>, <feDistantLight>, or <feSpotLight> children elements.

| LIVE PREVIEW

<feDisplacementMap>

Use the pixel values from in2 to spatially displace the pixels from in:

P(x,y)P(x+s(XC(x,y)0.5),y+s(YC(x,y)0.5)) P'(x,y) ← P\big( x + s \cdot (\mathrm{XC}(x,y) - 0.5),\,y + s \cdot (\mathrm{YC}(x,y) - 0.5)\big)

where P(x,y)P(x,y) is the input image (in), P(x,y)P'(x, y) is the destination, ss is the scale, XC(x,y)\mathrm{XC}(x,y) and YC(x,y)\mathrm{YC}(x,y) are the component values of the channel designated by the xChannelSelector and yChannelSelector.

  • in input image to be displaced
  • in2 input image that governs how we displace in
  • scale displacement scale factor (see above)
  • xChannelSelector which channel to use to displace the pixels in in along the x-axis; specify R, G, B, or A (default is A)
  • yChannelSelector which channel to use to displace the pixels in in along the y-axis; specify R, G, B, or A (default is A)
| LIVE PREVIEW

<feDropShadow>

Creates a drop shadow of the input image.

  • dx x offset of the drop shadow
  • dy y offset of the drop shadow
  • stdDeviation the standard deviation for the blur operation in the drop shadow
  • flood-color color of the shadow
  • flood-opacity opacity of the shadow
| LIVE PREVIEW

<feFlood>

Fills the filter subregion with a color.

  • flood-color color of the fill
  • flood-opacity opacity of the fill
| LIVE PREVIEW

<feGaussianBlur>

Applies a gaussian blur.

  • in the input image
  • stdDeviation the standard deviation for the blur operation
  • edgeMode how to handle the case near the edge of the input image; specify duplicate, wrap, or none (default)
| LIVE PREVIEW

<feImage>

Fetches the image data from an external source and provides the pixel data as output (if the external source is an SVG image, it is rasterized).

  • href URL to the image
  • preserveAspectRatio see preserveAspectRatio (default is xMidYMid meet)
| LIVE PREVIEW

<feMerge>

Allows you to show/merge multiple results at once.

<feMerge> expects you to put <feMergeNode> elements as its children. (<feMergeNode> only accepts the attribute in.)

| LIVE PREVIEW

<feMorphology>

Erodes or dilates the input image (thickens or thins it).

  • in the input image
  • operator erode (default) or dilate
  • radius radius for the operation
| LIVE PREVIEW

Normal text

Thinned text

Fattened text

<feOffset>

Offsets the input image.

  • in the input image
  • dx offset in the x axis
  • dy offset in the y axis

<feTile>

Fill a target rectangle with a repeated, tiled pattern of an input image. The effect is similar to the one of a <pattern>.

  • in the input image
| LIVE PREVIEW

<feTurbulence>

Creates an image using Perlin turbulence function.

  • type specify fractalNoise or turbulence (default)
  • baseFrequency the base frequency parameter(s) for the noise function (if two numbers are provided, the first number represents the base frequency for the x axis, and the other for the y axis)
  • numOctaves the number of octaves for the noise function (the higher this number is, the more natural the noise looks, but requires more computation)
  • seed the starting number for the pseudo random number generator
  • stitchTiles defines how the Perlin Noise tiles behave at the border; specify noStitch (default) or stitch
| LIVE PREVIEW

Light source elements

<fePointLight>

  • x, y, z position of light

<feSpotLight>

  • x, y, z position of light
  • pointsAtX, pointsAtY, pointsAtZ to where the light is pointing
  • specularExponent bigger means bricghter
  • limitingConeAngle angle in degrees between the spot light axis (between the light source and the point to which it is pointing); no light is projected outside the cone.

<feDistantLight>

  • azimuth the direction angle for the light source on the xy-plane (clockwise), from the positive x-axis. (Controls which side/edge of the shape is reflecting the light.)
  • elevation the direction angle for the light source from the XY plane towards the Z-axis.
Illustration of azimuth and elevation angles
Illustration of azimuth and elevation angles (Source: W3C)

References