I’ve been wanting to write an article on SVG filters for a long time, because they make CSS even more powerful. Take it to the next level using only CSS/HTML/SVG. The subject is the Cloud effect achieved by teacher Yuan Chuan using SVG filter — Codepen Demo — Cloud (SVG filter + CSS).

What is an SVG filter

SVG filters, similar to CSS filters, are a mechanism for creating complex effects in SVG. Many people are put off by the complex syntax of SVG filters. This article tries to be as concise as possible to understand how to use SVG filters.

This article assumes that the reader already has some basic concepts and usage of SVG.

Types of SVG filters

SVG filters include:

feBlend
feColorMatrix
feComponentTransfer
feComposite
feConvolveMatrix
feDiffuseLighting
feDisplacementMap
feFlood
feGaussianBlur
feImage
feMerge
feMorphology
feOffset
feSpecularLighting
feTile
feTurbulence
feDistantLight
fePointLight
feSpotLight

It looks a lot like the different features in CSS filters: blur(), contrast(), and drop-shadow().

Syntax for SVG filters

We need to define an SVG filter with the

and

tags.

Usually all SVG filter elements need to be defined inside the

tag.

Now, basically modern browsers, even if not used
<defs>The parcel
<filter>, you can also define an SVG filter.

The

tag is an acronym for definitions, and can contain many other labels, including various filters.

Second, the

tag is used to define the SVG filter. The

tag requires an id attribute, which is the flag of the filter. SVG graphics use this ID to reference the filter.

Take a look at a simple DEMO:

<div class="cssFilter"></div>
<div class="svgFilter"></div>

<svg>
    <defs>
        <filter id="blur">
            <feGaussianBlur in="SourceGraphic" stdDeviation="5" />
        </filter>
    </defs>
</svg>
div {
    width: 100px;
    height: 100px;
    background: #000;
}
.cssblur {
    filter: blur(5px);
}
.svgFilter{
    filter: url(#blur);
}

Here, we use SVG’s feGaussianBlur filter, which is also called blur filter, in the filter tag of defs. The filter has two attributes of in and stdDeviation. The In =”SourceGraphic” attribute indicates the blur effect to be applied to the entire image, and the stdDeviation attribute defines the degree of blur. Finally, in CSS, we use filter: url(#blur) to call the filter with ID of blur defined in HTML.

For the convenience of understanding, we also use CSS filter: blur(5px) to implement a similar filter, easy to compare, the result is as follows:

Codepen Demo – SVG Filter

Hey, as you can see, using the SVG blur filter, we have achieved the same effect as the CSS blur filter.

The URL pattern of the CSS Filter

Filter is used in the example above: The URL (#blur) pattern introduces an SVG filter effect. URL is one of the keywords for CSS filter properties. The URL pattern is one of the capabilities provided by CSS filters that allows us to introduce specific SVG filters, which greatly enhances the power of filters in CSS.

The equivalent of all SVG filter effects can be quickly introduced with the CSS filter URL mode.

Multiple filters work together

Like CSS filters, SVG filters allow you to mix and match multiple filters.

So we often see a

tag with a lot of code in it. It’s easy to get confused

Here’s a simple example:

<div></div> <svg> <defs> <! -- Filter declaration --> <filter id="MyFilter"> <! -- offsetBlur --> <feGaussianBlur in="SourceAlpha" stdDeviation="5" result="blur" /> <feOffset in="blur" dx="10" dy="10"  result="offsetBlur" /> <! -- merge SourceGraphic + offsetBlur --> <feMerge> <feMergeNode in="offsetBlur" /> <feMergeNode in="SourceGraphic" /> </feMerge> </filter> </defs> </svg>
div {
    width: 200px;
    height: 200px;
    background: url(xxx);
    filter: url(#MyFilter);
}

Let’s take a look at the final result of the filter. It looks like this:

It’s amazing how much code SVG uses to do something that CSS can do in a single line of code. (Of course, CSS is also difficult to implement here, not the simple container shadow, but PNG image shape contour shadow)

Decomposition steps

First look at this passage:

<! -- offsetBlur --> <feGaussianBlur in="SourceAlpha" stdDeviation="5" result="blur" /> <feOffset in="blur" dx="10" dy="10"  result="offsetBlur" />

< fegaussianBlur in=” sourceAlpha “stdDeviation=”5″ result=”blur” />, which we’ve already mentioned above, will create a blur effect, there’s a new attribute result=’blur’, One of the features of SVG is that the effects of different filters can be used to produce an intermediate result (also called primitives). Other filters can use the in attribute to import the results from different filters and continue with the process.

Next, the

filter is easy to understand, using in to take the result of the previous step, result = ‘blur’, and then make a simple shift.

An important point here is that by using the result and in properties in different filters, you can create an operation on top of a basic transform operation, such as adding a blur and then adding a shift effect in our example.

Combining the two filters, the result looks like this:

The original image is also present in the actual effect, so here we also use the

tag to combine multiple effects. That’s the code above:

<! -- merge SourceGraphic + offsetBlur --> <feMerge> <feMergeNode in="offsetBlur" /> <feMergeNode in="SourceGraphic" /> </feMerge>

The feMerge filter allows you to apply filter effects simultaneously rather than sequentially. You can do this by using result to store the output of other filters, which you then access in a

child element.

  • <feMergeNode in="offsetBlur" />Represents the final output of the above two filtersoffsetBlur That’s the part of the shadow
  • <feMergeNode in="SourceGraphic" />In thein="SourceGraphic"The keyword indicates that the graphic element itself will act as<filter>The raw input to the primitive

As a whole, the higher the level of the input is, the final result is obtained. The schematic flow chart is as follows:

At this point, you have basically mastered how SVG filters work, and how to use multiple filters together. Next, you just need to understand what the different filters can produce and what the different properties are, and you will have a basic understanding of SVG filters.

Something else to know about SVG filters

The above overview of how to use SVG filters has covered some properties and may have missed some, but this section will provide more details.

Filter tag generic properties

There are a number of attributes that can be set on every filter tag.

attribute role
x, y Provides the upper-left coordinates to define where to render the filter effect. (Default: 0)
width, height Draws the height and width of the filter container box (default is 100%)
result The output name used to define one filter effect so that it can be used as the input (in) for another filter effect
in Specifies the input source for the filter effect, which can be exported by a filterresult, or it could be the following six values

The six values of the in property

The in attribute in the SVG filter specifies the input source of the filter effect, which can be either the result exported by a filter or the following six values:

inThe values role
SourceGraphic This keyword indicates that the graphic element itself will act as<filter>The raw input to the primitive
SourceAlpha This keyword indicates that the graphic element itself will act as<filter>The raw input to the primitive.SourceAlpha 与 SourceGraphicHas the same rules exceptSourceAlphaUse only the opaque parts of the element
BackgroundImage Similar to SourceGraphic, but can be used on background. Explicit Settings are required
BackgroundAlpha Similar to SourceAlpha, but can be used for context. Explicit Settings are required
FillPaint Place it on an infinite plane using the fill paint
StrokePaint Use Stroke as if you put it on an infinite plane

The last 4 are basically useless ~

More on SVG filters

A few filters have already been mentioned, so let’s review them briefly:

  • <feGaussianBlur >– Blur filter
  • <feOffset >– Displacement filter
  • <feMerge>– Multi-filter stack filter

Here are some of the more common and interesting SVG filters.

FeBlend filter


is a blend mode filter, similar to the blend mode in CSS.

In CSS, we have mix-blend-mode and background-blend-mode. I’ve written a number of articles on the application of CSS blending patterns. If you’re not familiar with blending patterns in CSS, check out these articles:

  • The incredible mix-blend-mode
  • Incredible background-blend-mode
  • Creative CSS – Use Background to create all kinds of beautiful backgrounds

There are fewer types of blend modes in SVG than in CSS, only 5, which work exactly the same way as CSS blend modes:

  • Normal, normal
  • Multiply — Multiply
  • Screen – screen
  • Darken – dimmed
  • Lighten – brighten

In a simple Demo, we have two pictures, using different mixing modes, we can get different mixing results:

<div></div>

<svg>
    <defs>
        <filter id="lighten" x="0" y="0" width="200" height="250">
            <feImage width="200" height="250" xlink:href="image1.jpg" result="img1" />
            <feImage width="200" height="250" xlink:href="image2.jpg" result="img2" />
            <feBlend mode="lighten" in="img1" in2="img2"/>
        </filter>
    </defs>
</svg>
.container {
    width: 200px;
    height: 250px;
    filter: url(#lighten);
}

A

filter is also used, which is used to provide pixel data as output, and if the external source is an SVG image, the image will be raster.

The above results apply mode=”lighten” in the FeBlend filter, and the two images are superimposed to lighten blending mode:

Take a look at the effect of all 5 of the mixed modes:

CodePen Demo — SVG Filter feBlend Demo

feColorMatrix


filter is also one of the more interesting filters in SVG. As the name implies, it contains the word matrix in its name, which means that the filter transforms colors based on a transformation matrix. The color value of each pixel (a vector represented as [red, green, blue, transparency]) is a new color computed by matrix multiplicated.

This filter is a little bit more complicated, so let’s go through it step by step.


filter has two private attributes of type and values. Type supports four different types: Saturate | hueRotate | luminanceToAlpha | matrix, some of them are similar to some of the CSS Filter Filter effects.

typetype role valuesRange of values of
saturate Converted image saturation 0.0-1.0
hueRotate Convert image hue 0.0-360.
luminanceToAlpha Alpha channel brightness (SAD) There is only one effect, no need to change the value of values
matrix Use matrix functions for color transformation I have to apply a 4 x 5 matrix

Here, I made a simple about < feColorMatrix > before three attributes saturate | hueRotate | luminanceToAlpha indicated the effect of the DEMO – CodePen – feColorMatrix DEMO, To get a feel for their specific effects:

Saturate and hueRotate filters work exactly the same way as saturate and hue-rotate in the filters in CSS.

The type = feColorMatrix matrix

The type=matrix in fecolorMatrix is a little more complicated to understand, and its values need to be passed in a 4×5 matrix.

Something like this:

<filter id="colorMatrix">
  <feColorMatrix type="matrix" values="1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0"/>
</filter>

To understand how to use these filling matrices, we have to confront another problem — the representation of images.

The essence of digital image is a multi-dimensional matrix. When the image is displayed, we put the R component of the image in the red channel, the B component in the blue channel, and the G component in the green channel. After a series of processing, what appears on the screen is what we see as a color image.

The matrix matrix in feColorMatrix is used to represent the values of different channels and the values of each component. Finally, the value known to us as rgba() is obtained through calculation.

The calculation logic is as follows:

/* R G B A 1 */ 
1 0 0 0 0 // R = 1*R + 0*G + 0*B + 0*A + 0 
0 1 0 0 0 // G = 0*R + 1*G + 0*B + 0*A + 0 
0 0 1 0 0 // B = 0*R + 0*G + 1*B + 0*A + 0 
0 0 0 1 0 // A = 0*R + 0*G + 0*B + 1*A + 0

FecolorMatrix: FecolorMatrix: FecolorMatrix: FecolorMatrix: FecolorMatrix: FecolorMatrix

Just to use it, there’s also a visual DEMO, the codepen-fecolormatrix DEMO, to help you understand memory:


So far, most of the SVG filters have been presented with CSS capabilities, so what makes SVG filters unique and attractive? Is there anything CSS capabilities can’t do? Let’s take a look at some other interesting SVG filters.

FeSpecularLighting/feDiffuseLighting light filters

FESpecularLighting and Fediffuselighting both mean light filters and can be used to illuminate a source pattern. The difference is that FESpecularLighting is for specular lighting and Fediffuselighting is for scattered light lighting.

  • Fediffuselighting: from external light source, suitable for simulating sunlight or lighting
  • FESpecularLighting: Specifies the secondary light reflected from the reflecting surface

Take a quick look at one of the demos. The code looks a bit long, but it’s easy to understand step by step:

<div></div> <div class="svg-filter"></div> <svg> <defs> <filter id="filter"> <! -- SpecularLighting in="SourceGraphic". They are < SpecularLighting ="SourceGraphic". They are ="20"  <fePointLight x="0" y="0" z="200" /> </feSpecularLighting> <! --Composition of inputs--> <feComposite in="SourceGraphic" in2="spec" operator="arithmetic" k1="0" k2="1" k3="1" k4="0" /> </filter> </defs> </svg>
div {
    background: url(avator.png);
}
.svg-filter {
    filter: url(#filter);
}

On the left is the original image, and on the right is the effect after applying the light filter.

CodePen – feSpotLight SVG Light Source

FeMorphology filter

Femorphology is a morphological filter whose input source is usually the alpha channel of the graph, and two operations used for it can cause the source graph to corrode (thin) or expand (bold).

Use the attribute operator to determine whether you want the etching effect or the expanding effect. Use the property radius to indicate the degree of effect, which can be understood as the size of a stroke.

  • Operator:erodeErosion mode,dilateIs expansion mode, default iserode
  • Radius: The size of the stroke, which takes a number to indicate how effective it is in this mode. Default is 0

Let’s simply apply this filter to the text to see the effect:

<div class="g-text">
    <p>Normal Text</p>
    <p class="dilate">Normal Text</p>
    <p class="erode">Normal Text</p>
</div>

<svg width="0" height="0">
    <filter id="dilate">
        <feMorphology in="SourceAlpha" result="DILATED" operator="dilate" radius="3"></feMorphology>
    </filter>
    <filter id="erode">
        <feMorphology in="SourceAlpha" result="ERODE" operator="erode" radius="1"></feMorphology>
    </filter>
</svg>
p {
    font-size: 64px;
}
.dilate {
    filter: url(#dilate);
}
.erode {
    filter: url(#erode);
}

The effect is as follows: the far left is normal text, the middle is expansion mode, the right is corrosion mode, look at the effect, it is very easy to understand:

Of course, we can also apply it to images, where instead of simply making the strokes thicker or thinner,

  • forerodeMode, which changes each pixel of the image in a darker and more transparent direction,
  • whiledilateMode, which changes each direction to be brighter and more opaque around the pixel

In a simple animation DEMO, we have two graphs that use operator=”erode” and operator=”dilate” and dynamically change their radius. The code for one of them looks like this:

<svg width="450" height="300" viewBox="0 0 450 300"> <filter id="morphology"> <feMorphology operator="erode" radius="0">  <animate attributeName="radius" from="0" to="5" dur="5s" repeatCount="indefinite" /> </feMorphology> </filter> <image xlink:href="image.jpg" width="90%" height="90%" x="10" y="10" filter="url(#morphology)"></image> </svg>

The image above shows expansion mode on the left and corrosion mode on the right:

CodePen Demo — SVG feMorphology Animation

FeTurbulence filter

Turbulence means turbulence and instability, while the SVG

filter creates translucent, smoky or undulating images. Usually used to implement some special texture. The filter uses the Perlin noise function to create an image. Noise is very useful in simulating cloud effects and can produce very complex textures. It can be used to synthesize artificial textures such as moire and marbling.

With FeturBulence, you can create your own texture graphics as displacement graphs using SVG without resorting to the texture effects of external graphics to create complex graphics effects.

This filter, in my opinion, is one of the most interesting SVG filters, because it allows us to create some textures ourselves, and then superimpose them on top of other effects to create a very interesting motion effect.

FeturBulence has three properties that we need to pay special attention to: type, baseFrequency, numOctaves:

  • Type: The type of filter to be implemented, either FractalNoise or Turbulence Noise.

    • Fractalnoise: Fractal noise is smoother, and the noise it produces feels more like a cloud
    • Turbulence: Turbulence
  • Basefrequency: the parameter representing the basic frequency of the noise function. The smaller the frequency is, the larger the graph will be generated; the larger the frequency is, the more complex the noise will be, and the smaller and more refined the graph will be. The usual value range is 0.02 ~ 0.2
  • NuMoctaves: Represents the fineness of the noise function. The higher the value, the more detailed the noise will be. The default value is 1

There is a very good website for scheming the effects of the two noises produced by FeturBulence: http://apike.ca/ – FeturBulence

The code of the two kinds of noise is basically the same, only the type is different:

<filter ID ="fractal" > <feTurbulence ID =" Fe-turb-fractal "type=" Fractalnoise" baseFrequency="0.00025" numOctaves="1"/> </filter> <filter id=" Turbu "> <feTurbulence id=" FE-Turb-Turbulence "type=" Fractalnoise" baseFrequency="0.00025" numOctaves="1"/> </filter>

We change the parameters of Basefrequency and NuMoctaves to see the effects of the two kinds of noises actually generated:

At the same time, baseFrequency allows us to pass in two values, we can only change the frequency in a certain direction, you can check this Demo: CodePen — feTurbulence baseFrequency & numOctaves

A single < feTurbulence > filter is difficult to understand this filter to stem what of, need to the filter as a texture or input, collocation is used together with other filters, achieve some effects, let’s look at:

Use the FeturBulence filter to achieve the effect of text flow

First, try to combine the texture generated by feturBulence with the text.

The simple code is as follows:

<div>Coco</div> <div class="turbulence">Coco</div> <svg> <filter id="fractal" filterUnits="objectBoundingBox" x="0%" Y ="0%" width="100%" height="100%"> < feturBulence id=" Turbulence "type=" Fractalnoise" baseFrequency="0.03" NuMoctaves ="1"  /> <feDisplacementMap in="SourceGraphic" scale="50"></feDisplacementMap> </filter> </svg>
.turbulence {
    filter: url(#fractal);
}

On the left is the normal effect and on the next is the effect with < feturBulence > applied. You can try to click in Demo and change the size of BasefRequency and NuMoctaves parameters to see different effects:

CodePen Demo — feTurbulence text demo

FedisPlacementMap mapping displacement filter

The Demo above also uses the FedisPlacementMap filter, which also needs a brief explanation.

FedisplacementMap is a replacement filter for mapping. It is not easy to use this filter well, and requires a lot of knowledge about Photoshop texture creation or graphic color. This filter replaces the pixel value of the image from the input value in to the space with the pixel value from the input value in to the space from the image.

In human terms, a fedisplacementMap is actually used to change the pixel position of elements and graphics. This filter forms a new shape by iterating over all the pixels of the original shape and remapping them to a new location using a fedisplacementMap.

In the combination of the above FeturBulence filter and text, we obtained the noise figure through the FeturBulence noise, and then used the FedDisplacementMap filter to deform, distort and liquefy the noise figure generated by the FeturBulence. To get the final result.

In MDN there is a formula for this filter conversion (interested can study, I can not bite) :

P '(x, y) please P (x + scale * (XC (x, y) - 0.5), y + scale * (YC (x, y) - 0.5))

Use the FeturBulence filter to texture the folded paper

OK, let’s move on to FeturBulence. With this filter, we can generate a variety of different textures. We can try to use the FeturBulence filter with the Light filter to create a wrinkled paper texture with very little code:

<div></div> < SVG >< filter id='roughpaper'> <feTurbulence type="fractalNoise" baseFrequency='0.04' result='noise' numOctaves="5" /> <feDiffuseLighting in='noise' lighting-color='#fff' surfaceScale='2'> <feDistantLight azimuth='45' elevation='60' /> </feDiffuseLighting> </filter> </svg>
div {
    width: 650px;
    height: 500px;
    filter: url(#roughpaper);
}

The effect is as follows:

CodePen Demo — Rough Paper Texture with SVG Filters

You can find a tutorial on how to make SVG Filters on YouTube — SVG Filters Crash Course by Sara Soueidan in a post on SVG Filters

Use feturBulence filter to achieve button hover effect

You can also create some very interesting button effects using the FeturBulence filter with the FedDisplacementMap filter.

Try implementing some failover style buttons, one of which has the following code:

<div class="fe1">Button</div> <div class="fe2">Button</div> <svg> <defs> <filter id="fe1"> <feTurbulence id="animation" Type =" Fractalnoise "baseFrequency="0.00001 9.9999999" numOctaves="1" result="warp"> <animate AttributeName ="baseFrequency" from="0.00001 9.9999" to="0.00001 0.001" dur="2s" repeatCount="indefinite"/> </feTurbulence> <feOffset dx="-90" dy="-90" result="warpOffset"></feOffset> <feDisplacementMap xChannelSelector="R" yChannelSelector="G" scale="30" in="SourceGraphic" in2="warpOffset"></feDisplacementMap> </filter> </defs> </svg>
.fe1 {
    width: 200px;
    height: 64px;
    outline: 200px solid transparent;
}

.fe1:hover {
    filter: url(#fe1);
}

When passing the hover button, add a filter effect to the button, and the filter itself has an animation with an infinite loop:

The full code you can stamp here: CODEPEN-SVG Filter Button Effects

Use the FeturBulence filter to achieve the cloud effect

Finally, let’s go back to the cloud effect in the image above. Using the FeturBulence filter, we can simulate the real cloud effect in SVG very realisedly.

First, implement this single figure by randomly generating multiple box-shadows:

<div></div>
div {
    width: 1px;
    height: 1px;
    box-shadow: rgb(240 255 243) 80vw 11vh 34vmin 16vmin, rgb(17 203 215) 33vw 71vh 23vmin 1vmin, rgb(250 70 89) 4vw 85vh 21vmin 9vmin, rgb(198 241 231) 8vw 4vh 22vmin 12vmin, rgb(198 241 231) 89vw 11vh 31vmin 19vmin, rgb(240 255 243) 5vw 22vh 38vmin 19vmin, rgb(250 70 89) 97vw 35vh 33vmin 16vmin, rgb(250 70 89) 51vw 8vh 35vmin 14vmin, rgb(17 203 215) 75vw 57vh 40vmin 4vmin, rgb(250 70 89) 28vw 18vh 31vmin 11vmin, rgb(250 70 89) 8vw 89vh 31vmin 2vmin, rgb(17 203 215) 13vw 8vh 26vmin 19vmin, rgb(240 255 243) 98vw 12vh 35vmin 5vmin, rgb(17 203 215) 35vw 29vh 27vmin 18vmin, rgb(17 203 215) 67vw 58vh 22vmin 15vmin, rgb(198 241 231) 67vw 24vh 25vmin 7vmin, rgb(17 203 215) 76vw 52vh 22vmin 7vmin, rgb(250 70 89) 46vw 86vh 26vmin 20vmin, rgb(240 255 243) 50vw 20vh 25vmin 1vmin, rgb(250 70 89) 74vw 14vh 25vmin 16vmin, rgb(240 255 243) 31vw 100vh 29vmin 20vmin
}

This can be done by a language like Sass, Less, or JavaScript that has the ability to loop functions. It looks something like this:

Next, the fractal noise image is generated by feturBulence, the map is replaced by a fedisplacementMap, and finally the filter effect is overlaid on the image.

<svg width="0">
  <filter id="filter">
    <feTurbulence type="fractalNoise" baseFrequency=".01" numOctaves="10" />
    <feDisplacementMap in="SourceGraphic" scale="240" />
  </filter>
</svg>
div {
    filter: url(#filter);
}

To get this cloud effect:

Cloud (SVG Filter + CSS) Cloud (SVG Filter + CSS)

To summarize

This article briefly introduces the use of SVG filters and some common SVG filters and gives the most simple use of some effects, I hope you can have a simple understanding of SVG filters after reading.

The filter effects listed in this article are more of a single effect or a few combined effects, the actual use or application of the application scene is actually a combination of more filter effects produced.

Later articles will explore and analyze the effects of multiple SVG filter combinations in more detail, and explore more complex permutations and combinations.

The title of the article is SVG Filters from Getting Started to Getting Done because SVG Filters are too cumbersome to learn, and it’s not as easy to learn as CSS Filters or Blending Patterns. It also has to do with the fact that SVG filters are very powerful, very customizable, and have been around for a long time. SVG filters are also very compatible; they actually predate some of the special effects of CSS3.

CSS has been drawing closer to the special capabilities of SVG, making it easier to use with a simpler syntax, but SVG filters still have their own unique appeal. There will be more articles on SVG filters in the future. I also hope that the students who read here will not give up!

The resources

  • Rounding feColorMatrix
  • In-depth understanding of the SVG FedDisplacementMap filter and its practical application
  • SVG tutorialspoint
  • apike.ca – SVG Filter
  • FILTER EFFECTS
  • Youtube – SVG Filter Effects | feTurbulence
  • Youtube – SVG Filters Crash Course
  • DistortedButtonEffects

The last

Well, that’s the end of this article, I hope to help you πŸ™‚

More exciting CSS technical articles in my GitHub — ICSS, keep updating, welcome to click star to subscribe to the favorites.

Want to Get the most interesting CSS information, do not miss my public number – ICSS front end stories πŸ˜„

If there are any questions or suggestions, you can communicate more, the original article, the writing is limited, the talent is shallow, if there is something wrong in the article, wang told.