significant! Powerful SVG filter


I’ve wanted to write an article about SVG filter for a long time. The existence of SVG filter makes CSS, which is already very powerful, even stronger. Take the effect of just using CSS / HTML / SVG to a higher level. The picture shows the cloud effect achieved by Mr. Yuan Chuan using SVG filter–CodePen Demo — Cloud (SVG filter + CSS)

What is an SVG filter

Svg filter is similar to CSS filter. It is a mechanism used to create complex effects in SVG. Many people see the complex syntax of SVG filter, which is easy to retreat. This paper tries to use the most concise and clear way to let everyone understand the use of SVG filter as much as possible.

The default readers of this article have mastered the basic concepts and usage of SVG.

Types of SVG filters

Svg filter includes:


There are many contents, which are similar to different functions in CSS filter:blur()contrast()drop-shadow()

Syntax of SVG filter

We need to use<defs>and<filter>Label to define an SVG filter.

Generally, all SVG filter elements need to be defined in<defs>Inside the tag.

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

this<defs>Tags are short for definitions and can contain many other tags, including various filters.

Second, use<filter>Tags are used to define SVG filters.<filter>The tag needs an ID attribute, which is the flag of the filter. Svg graphics use this ID to reference the filter.

Look at a simple demo:

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

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

Here we aredefsoffilterIn the label, SVG is usedfeGaussianBlurThe filter, that is, the blur filter, has two propertiesinandstdDeviation。 amongin="SourceGraphic"Property indicates that the blur effect is to be applied to the entire picture,stdDeviationAttribute defines the degree of ambiguity. Finally, in CSS, thefilter: url(#blur)The ID defined in the html isblurFilter.

CSS filters are also used for ease of understandingfilter: blur(5px)A similar filter is implemented to facilitate comparison. The results are shown as follows:

significant! Powerful SVG filter

Codepen Demo – SVG filter

Hey, you can see that using SVG fuzzy filter achieves the same effect as CSS fuzzy filter.

URL pattern of CSS filter

Used in the example abovefilter: url(#blur)This mode introduces an SVG filter effect. URL is one of the keywords of CSS filter properties,urlPattern is one of the capabilities provided by CSS filters, which allows us to introduce specific SVG filters, which greatly enhances the capabilities of filters in CSS.

It is equivalent to all filter effects realized through SVG, which can be quickly introduced through CSS filter URL mode.

Multiple filters work together

Like CSS filters, SVG filters also support the combination of multiple filters.

So we often see one<filter>There are a lot of codes in the tag. It’s easy to get confused~

Let’s take another simple example:


        <!-- 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 -->
                <feMergeNode in="offsetBlur" />
                <feMergeNode in="SourceGraphic" />
div {
    width: 200px;
    height: 200px;
    background: url(xxx);
    filter: url(#MyFilter);

Let’s take a look at the final result of the whole filter. The result is as follows:

significant! Powerful SVG filter

CSS can be implemented in one line of code. SVG actually uses so much code. (of course, CSS here is not easy to implement, not the shadow of a simple container, but the outline shadow of PNG image graphics)

Decomposition steps

First look at this paragraph:

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

first<feGaussianBlur in="SourceAlpha" stdDeviation="5" result="blur" />This paragraph, as we mentioned above, will generate a blur effect. Here is a new attributeresult='blur', this is a feature of SVG. The effect of different filters can be determined byresultProduces an intermediate result (also known as primitives) that other filters can useinProperty to import the output of different filtersresult, continue.

Then,<feOffset>The filter is easy to understand and can be usedinGot the result of the previous stepresult = 'blur'And then do a simple displacement.

Here is a very important knowledge point:Use in different filtersresultandinProperty to create another operation on top of the previous basic transformation operationFor example, in our example, we add blur and then add displacement effect.

The graphic effect produced by combining two filters is actually as follows:

significant! Powerful SVG filter

The original image also appears in the actual effect, so we also use it here<feMerge>Label, merging multiple effects. That is, the above code:

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

feMergeFilters allow you to apply filter effects simultaneously rather than sequentially. utilizeresultStoring the output of other filters can achieve this, and then in one<feMergeNode>Access it in child elements.

  • <feMergeNode in="offsetBlur" />The final output results of the above two filters are shownoffsetBlur That is, the shadow part
  • <feMergeNode in="SourceGraphic" />Mediumin="SourceGraphic"The keyword indicates that the graphic element itself will be<filter>Primitive input

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

significant! Powerful SVG filter

So far, I have basically mastered the working principle of SVG filter and how to use multiple filters together. Next, you only need to understand what effects different filters can produce and what different attributes they have, so you can have a basic grasp of SVG filters!

What else to know about SVG filter

The use process of SVG filter has been briefly described above. Some attributes have been mentioned in the process, and some attributes may have been omitted. This chapter will supplement them.

Filter label general properties

There are some properties that each filter label has and can be set.

attribute effect
x, y Provide the coordinates of the upper left corner to define where the filter effect is rendered. (default: 0)
width, height Draw the height and width of the filter container frame (100% by default)
result Defines the output name of one filter effect so that it can be used as input to another filter effect (in)
in Specify the input source of filter effect, which can be exported by a filterresult, or the following 6 values

6 values of in attribute

In SVG filterinProperty to specify the input source of the filter effect, which can be exported by a filterresult, or the following 6 values:

inValue effect
SourceGraphic This keyword indicates that the graphic element itself will be<filter>Primitive input
SourceAlpha This keyword indicates that the graphic element itself will be<filter>The original input of the primitive.SourceAlphaAndSourceGraphicHave the same rules exceptSourceAlphaUse only the non transparent part of the element
BackgroundImage Similar to sourcegraphic, but can be used in the background. Explicit settings are required
BackgroundAlpha Similar to sourcealpha, but can be used in the background. Explicit settings are required
FillPaint Fill paint as if it were placed on an infinite plane
StrokePaint Use stroke painting just like placing it on an infinite plane

The last four are basically useless~

More introduction to SVG filter

Several filters have been mentioned above. Let’s briefly review:

  • <feGaussianBlur >-Blur filter
  • <feOffset >-Displacement filter
  • <feMerge>-Multi filter superposition filter

Next, we will introduce some common and interesting SVG filters.

Feblend filter

<feBlend>It is a mixed mode filter, which is similar to the mixed mode in CSS.

In CSS, we have mixed modemix-blend-modeandbackground-blend-mode。 I’ve had many articles about some applications related to CSS mixed mode. If you don’t know much about the blending mode in CSS, you can take a look at these articles first:

The types of mixed modes in SVG are less than those in CSS, with only 5. Their functions are completely consistent with those in CSS:

  • Normal – normal
  • Multiply – multiply positive
  • Screen – color filter
  • Dark – darken
  • Lighten – lighten

In a simple demo, we have two diagrams. Different mixing results can be obtained by using different mixing modes:


        <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"/>
.container {
    width: 200px;
    height: 250px;
    filter: url(#lighten);

Here’s another one<feImage>The function of filter is to provide pixel data as output. If the external source is an SVG image, the image will be rasterized.

significant! Powerful SVG filter

The above applicationfeBlendIn the filtermode="lighten"As a result, the two images superimpose the lighten blending mode:

significant! Powerful SVG filter

See the effects of all 5 blending modes:

significant! Powerful SVG filter

CodePen Demo — SVG Filter feBlend Demo


<feColorMatrix>Filter is also a very interesting filter in SVG filter. As its name implies, its name contains the word matrix, indicating that the filter is based onTransformation matrixChange the color. The color value of each pixel (a vector expressed as [red, green, blue, transparency]) is a new color calculated by matrix multiplated.

This filter is a little complicated. Let’s look at it step by step.

<feColorMatrix>The filter has 2 private propertiestypeandvaluesType, which supports four different types:saturate | hueRotate | luminanceToAlpha | matrix, some of which are similar to some filters in CSS filter.

typetype effect valuesValue range of
saturate Convert image saturation 0.0 – 1.0
hueRotate Convert image hue 0.0 – 360
luminanceToAlpha Alpha channel brightness There is only one effect and there is no need to change the value of values
matrix Color transformation using matrix function A 4 x 5 matrix needs to be applied

Here, I made a simple about<feColorMatrix>First 3 attributessaturate | hueRotate | luminanceToAlphaEffect of demo–CodePen – feColorMatrix Demo, you can feel their specific effects:

significant! Powerful SVG filter

The roles of as like as two peas in saturate, hueRotate filter and filter in CSS are exactly the same.

Type = matrix in fecolormatrix

feColorMatrixMediumtype=matrixIt’s a little more complicated to understand. Its values need to pass in a 4×5 matrix.

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"/>

To understand how to use these fill in matrices, we have to face another problem – image representation.

The essence of digital image is a multidimensional matrix. During image display, we put the R component of the image into the red channel, the B component into the blue channel and the G component into the green channel. After a series of processing, what is displayed on the screen is the color image we see.

The matrix matrix in fecolormatrix is used to represent the values of different channels and the values of each component. Finally, we can get the well-known values through calculationrgba()Value.

The calculation logic is:

/* 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

Chinese articles, rightfeColorMatrixThe best explanation of matrix should be the one given by Mr. desert–Explain fecolormatrix in detail, those interested in specific representations can have a look.

Just for use, there is also a visual demo–CodePen – feColorMatrix Demo, help people understand memory:

significant! Powerful SVG filter

So far, most of the display and explanation of SVG filters can be realized by the existing capabilities of CSS. What is the uniqueness and charm of SVG filters? Is there anything CSS can’t do? Let’s take a look at some other interesting SVG filters.

Fespecularlighting / fedifuselighting light filter

Fespecular lighting and fedifuselighting both mean lighting filters. They can illuminate a source image. The difference is that fespecular lighting is specular lighting and fedifuselighting is scattered light lighting.

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

Simply look at one of the demos. The code looks a little too much, but it’s easy to understand step by step:

<div class="svg-filter"></div>
        <filter id="filter">
            <!--Lighting effect-->
            <feSpecularLighting in="SourceGraphic" specularExponent="20" specularConstant="0.75" result="spec">
              <fePointLight x="0" y="0" z="200" />
            <!--Composition of inputs-->
            <feComposite in="SourceGraphic" in2="spec" operator="arithmetic" k1="0" k2="1" k3="1" k4="0" />
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 illumination filter.

significant! Powerful SVG filter

CodePen – feSpotLight SVG Light Source

Femorphology filter

Femorphology is a morphological filter. Its input source is usually the alpha channel of graphics. Its two operations can corrode (thin) or expand (BOLD) the source graphics.

Use propertiesoperatorDetermine whether to corrosion effect or expansion effect. Use propertiesradiusIndicates the degree of effect, which can be understood as the size of strokes.

  • operator:erodeCorrosion mode,dilateIt is expansion mode, and the default iserode
  • Radius: the size of the stroke. A number is accepted to indicate the effect degree in this mode. The 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>

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

The effects are as follows: the normal text is on the left, the expansion mode is in the middle, and the corrosion mode is on the right. Look at the effect, it’s very easy to understand:

significant! Powerful SVG filter

Of course, we can also apply it to the picture. At this time, it is not simply to make the strokes of the image thicker or thinner,

  • abouterodeMode, which will change each pixel of the picture to a darker and more transparent direction,
  • anddilateMode is to change each pixel to a brighter and more opaque direction around the pixel

Let’s take a brief look at an example animation demo. We have two pictures, which work respectivelyoperator="erode"andoperator="dilate"And dynamically change theirradius, one of the codes is shown as follows:

<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" />

    <image xlink:href="image.jpg" width="90%" height="90%" x="10" y="10" filter="url(#morphology)"></image>

significant! Powerful SVG filter

In the figure above, the expansion mode is on the left and the corrosion mode is on the right:

CodePen Demo — SVG feMorphology Animation

Feturbulence filter

Turbulence means turbulent, unstable air flow, and SVG<feTurbulence>The filter can achieve translucent smoke or wavy images. It is usually used to implement some special textures. The filter creates an image using the Perlin noise function. Noise is very useful in simulating cloud effect and can produce very complex texture. It can be used to realize the synthesis of artificial texture, such as moire and marble.

YesfeTurbulence, we can use SVG to create texture graphics as displacement graphics, and we can create complex graphics effects without using the texture effects of external graphics.

I personally think this filter is the most interesting one of SVG filters, because it allows us to create some textures by ourselves and superimpose them on other effects to produce very interesting dynamic effects.

feTurbulenceThere are three attributes that we should pay special attention to:typebaseFrequencynumOctaves

  • Type: the type of filter implemented; optionalfractalNoiseFractal noise, orturbulenceTurbulence noise.

    • Fractal noise: fractal noise is smoother, and its noise texture is closer to cloud
    • Turbulence: turbulence noise
  • Basefrequency: a parameter representing the basic frequency of the noise function. The smaller the frequency, the larger the graph generated. The larger the frequency, the more complex the noise generated. The smaller and finer the graph. The usual value range is 0.02 ~ 0.2
  • Numoctaves: indicates the fineness of the noise function. The higher the value, the more detailed the noise generated. The default value is 1

Here is a very good website for illustrationfeTurbulenceThe effect of two kinds of noise: – feTurbulence

The codes of the two kinds of noise are basically the same, excepttypeDifferent types:

<filter id="fractal" >
  <feTurbulence id="fe-turb-fractal" type="fractalNoise" baseFrequency="0.00025" numOctaves="1"/>
<filter id="turbu">
  <feTurbulence id="fe-turb-turbulence" type="fractalNoise" baseFrequency="0.00025" numOctaves="1"/>

We changebaseFrequencyandnumOctavesParameter to see the effect of two kinds of noise actually generated:

significant! Powerful SVG filter

At the same time,baseFrequencyAllow us to pass in two values. We can only change the frequency in one direction. Specifically, you can poke this demo to see:CodePen — feTurbulence baseFrequency & numOctaves

Just one<feTurbulence>In fact, it is difficult to understand what the filter wants to do. This filter needs to be used as texture or input together with other filters to achieve some effects. Let’s take a look at it below:

Use the feturbulence filter to achieve the effect of text flow

First, try tofeTurbulence The resulting texture is combined with text.

The simple code is as follows:

<div class="turbulence">Coco</div>

    <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>
.turbulence {
    filter: url(#fractal);

On the left is the normal effect, and on the back is the application<feTurbulence>You can try clicking into the demo to change the effectbaseFrequencyandnumOctavesDifferent effects can be seen according to the size of the parameter:

significant! Powerful SVG filter

CodePen Demo — feTurbulence text demo

Fedisplacementmap map map displacement filter

The above demo also usesfeDisplacementMapFilter, also need a simple explanation.

Fedisplacementmap is a mapping displacement filter. It is not easy to use this filter well. You need to master a lot of knowledge about Photoshop texture creation or graphic color. The filter replaces the pixel value of the image from the in input value to the space with the pixel value from the in2 input value to the space in the image.

Speaking human words isfeDisplacementMapIt is actually used to change the pixel position of elements and graphics. The filter traverses all pixels of the original image and usesfeDisplacementMapRemap to a new location to form a new graph.

In the abovefeTurbulenceIn the combination of filter and text, wefeTurbulenceThe noise pattern is obtained by noisefeDisplacementMapFilter according tofeTurbulenceThe generated noise pattern is deformed, distorted and liquefied to obtain the final effect.

stayMDNThere is a formula for the transformation of this filter (those interested can study it, I can’t chew it):

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

Texture of folded paper using feturbulence filter

OK, let’s go onfeTurbulence, using this filter, we can generate various textures, and we can try to use itfeTurbulenceThe filter is combined with the illumination filter to achieve the wrinkled paper texture effect, and there are very few codes:

    <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' />
div {
    width: 650px;
    height: 500px;
    filter: url(#roughpaper);

The effects are as follows:

significant! Powerful SVG filter

CodePen Demo — Rough Paper Texture with SVG Filters

You canSara SoueidanOn a share about SVG filter, find the tutorial for making it:Youtube — SVG Filters Crash Course

Use the feturbulence filter to achieve the button hover effect

usefeTurbulenceFilter matchingfeDisplacementMapFilter, you can also make some very interesting button effects.

Try to implement some fault style buttons. The code of one button is as follows:

<div class="fe1">Button</div>
<div class="fe2">Button</div>

        <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"/>
            <feOffset dx="-90" dy="-90" result="warpOffset"></feOffset>
            <feDisplacementMap xChannelSelector="R" yChannelSelector="G" scale="30" in="SourceGraphic" in2="warpOffset"></feDisplacementMap>
.fe1 {
    width: 200px;
    height: 64px;
    outline: 200px solid transparent;

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

When you pass the hover button, add a filter effect to the button, and the filter itself has an infinite loop Animation:

significant! Powerful SVG filter

The complete code you can stamp here:CodePen Demo – SVG Filter Button Effects

Cloud effect with feturbulence filter

Finally, let’s go back to the cloud effect on the title map and use itfeTurbulenceFilter, we can very realistically use SVG to simulate the real cloud effect.

First, through randomly generated multiplebox-shadow, realize this one figure:

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 work can be generated by sass, less or JavaScript, which can have the ability of circular functions. Its effect is roughly as follows:

significant! Powerful SVG filter

Then, throughfeTurbulenceGenerate fractal noise graphics, usingfeDisplacementMapMap and replace, and finally superimpose this filter effect on the graph.

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

You can get such a cloud effect:

significant! Powerful SVG filter

For the complete code, you can stamp here and watch it on Mr. Yuan Chuan’s codepen:Cloud (SVG filter + CSS)

To sum up

The first article about the introduction of SVG filter is almost finished. This paper briefly introduces the use of SVG filter and some common SVG filters, and gives some of the simplest use effects. I hope you can have a simple understanding of SVG filter after reading it.

The filter effects listed in this article are more single effects or a few combined effects. The actual use or application to the application scenario will actually be an effect produced by the combination of more filters.

Later articles will discuss and analyze the combination effect of multiple SVG filters in more detail and explore more complex arrangement and combination.

The title of the article isSvg filter from getting started to giving upBecause SVG filter is too cumbersome and tired to learn, it is not as easy to use as CSS filter or mixed mode. Of course, because the SVG filter is very powerful and customized, and it has existed for a long time. Svg filters are also very compatible. They actually existed before some special effects of CSS3.

CSS has been moving closer to some special capabilities of SVG, making it easier to use simpler syntax, but SVG filter still has its unique charm. There will be more articles on SVG filters in the future. I also hope the students who read here don’t give up!

reference material


Well, this article ends here. I hope it will help you:)

More wonderful CSS technical articles are summarized in myGithub — iCSS, continuously updated. Welcome to a star subscription collection.

If you want Get to get the most interesting CSS information, don’t miss my official account.ICSS front end anecdotes 😄

If you have any questions or suggestions, you can communicate more. The original articles have limited writing style and shallow talents. If there is anything wrong in the article, please let me know.

Recommended Today

Seven solutions for distributed transactions

1、 What is distributed transaction Distributed transaction means that transaction participants, transaction supporting servers, resource servers and transaction managers are located on different nodes of different distributed systems. A large operation is completed by more than n small operations. These small operations are distributed on different services. For these operations, either all of them are […]