This is my second article on SVG filters. This article introduces several primitives to bring external resources into the SVG filter construction process.

The image is introduced into

As the saying goes, one cannot make bricks without straw. If slut === SVG filter, then m === image. Therefore, for an SVG filter to work, we need to pass the image to be processed into the SVG filter primitive. So how do you do this?

Let’s take a look at some of the keywords and primitives that can be used to input images for SVG filters

The keyword used to reference the original image

These keywords can be used to input images as input values for the IN attribute of the image processing filter primitive.

SourceGraphic

Represents the element as it should have looked before the filter was applied (source image)

Let’s look at an example

This is the original image, which contains transparent pixels.

In order to facilitate the gesture, the author drew the checkerboard in this hand, by rgba(181,181,181,1) and rgba(21,21,21,21,0.3) two kinds of gray interleave, the application of filter effect part only gogoend pattern.

Let’s extract the SourceGraphic, the source image, from the original image

<filter id="filter">
    <feTile in="SourceGraphic"/>
</filter>
Copy the code

Available:

By default, if in is null, the value of in is SourceGraphic

SourceAlpha

Represents the transparent channel (Alpha of the source image) of the element before the filter is applied, as grayscale

[example 2-3]

Let’s extract the SourceAlpha in the original image [Example 2-1], that is, the Alpha channel in the source image

<filter id="filter">
    <feTile in="SourceAlpha"/>
</filter>
Copy the code

Available:

Here, the transparent pixels are all white, the opaque ones are all black, and the translucent ones are grey

The four keywords below – BackgroundImage, BackgroundAlpha, FillPaint, StrokePaint – can probably be skipped directly. The related images are just my guess rather than the actual results.

BackgroundImage

Represents the content behind the element on which the filter is currently applied

This primitive does not work after testing. According to the specification, the output of this primitive should be:

Since the result here is directly superimposed on the original image, and the original image is not introduced through other filters, the original image should disappear directly, leaving only the background. And the background that’s left here is integrated into the background, so I’ve drawn a red box here for the sake of presentation. The final result is the content of the red box (below the original image) (checkerboard here), which can be extracted to the next filter primitive for processing.

BackgroundAlpha

The Alpha channel representing the content behind the element currently being filtered, as a grayscale diagram

This primitive does not work after testing. According to the specification, the output of this primitive should be:

This is actually an Alpha channel with checkerboard output.Rgba (181181181, 1)The fill is shown as all white,Rgba (211211211,0.3)The fill is shown in a darker gray

FillPaint

Represents the fill in the element currently using the filter, of the element to which the filter is appliedfillattribute

This primitive does not work after testing. According to the specification, the output of this primitive should be:

That’s the fill part of the image

StrokePaint

Represents a stroke in the element currently using the filter, of the element applying the filterstrokeattribute

This primitive does not work after testing. According to the specification, the output of this primitive should be:

That’s the stroke part of the image

It is very embarrassing. After testing and checking various postpositions, none of the keywords BackgroundImage, BackgroundAlpha, FillPaint and StrokePaint seem to take effect in Chrome and Firefox, so I use the delete line to cross out the above description. The corresponding picture is just my guess. Although these values are specified in the specification, browsers may not implement them. Although MDN’s article SVG 1.1 Support in Firefox – SVG: Scalable Vector Graphics’ Filter Module ‘means that Firefox implemented FillPaint and StrokePaint in these four keywords, but they didn’t seem to work in my tests.

You can open CodePen to see a demo of these six keywords.

Filter primitive for generating images

Such primitives can be created from scratch or by importing images to generate the image source (input source) of an SVG filter, which can be referenced in the IN attribute of the image processing filter element below. This primitive has no in attribute and is dedicated to producing images. When using these primitives, if the source image SourceGraphic is not used through other primitives, the source images will be replaced with the images generated to replace them.

feFlood– fill

This primitive is used to fill an image with a certain color.

  • flood-color

    Set the fill color. The default is #000

  • flood-opacity

    Set the fill transparency. Default is 1

[example 2-4]

<filter xmlns="http://www.w3.org/2000/svg" id="filter">
    <feFlood flood-color="#e32247" flood-opacity="1" result="4CD827A1-2842-4D2D-BD12-FCF306D53C5D"/>
</filter>
Copy the code

feImage– Introduces external images

This primitive introduces an external image.

  • preserveAspectRatio

    Whether to preserve image proportions

    The default value is xMidYMid meet, which means that the incoming image will be placed in the middle of the filter element’s range, keeping it in proportion.

    We can see that the value accepted by this property is separated by Spaces, so the value is made up of two parts:

    [

    ].

    Align indicates how the short edges of the image are aligned. The default value is xMidYMid. Possible values include:

    1. None – Indicates that the image will be stretched to the full range of the filter. When set to this value, the image does not have to be cropped because it already covers the entire filter range, so the value of the second (meetOrSlice) will always be meet

    2. xMinYMin | xMinYMid | xMinYMax | xMidYMid | xMidYMin | xMidYMax |

    XMaxYMin | xMaxYMid | xMinYMax – the images will be geometric scaling, introduced said, but the image will be relatively effective filter range alignment.

    Although these attributes are a bit cumbersome to enumerate, we can summarize a table to see what they mean:

    x Y
    Min Align with the horizontal starting point of the filter’s range Align with the vertical starting point of the filter’s range
    Mid Align relative to the horizontal center of the filter’s range Align relative to the vertical center of the filter’s range
    Max Align with the horizontal end of the filter’s range Align with the vertical end of the filter’s range

    MeetOrSlice shows how the long edges outside the image range will be cropped when the imported image is scaled equally.

    1. meetThat is, no matter how scaled the image is, the long side will remain within the range of the filter. Right
    2. sliceThat is, after the introduced image is scaled, the long side will be out of the effective range of the filter
  • xlink:href / href

    The address of the external image. This attribute was previously xlink:href, but as defined in the specification, xlink:href has been discarded and href should now be used

Take the logo from a recent nuggets campaign as an example.

As shown in figure:

[example 2-5]

Import SVG with , and external images in SVG come from Data URL:

<filter xmlns="http://www.w3.org/2000/svg" id="filter">
    <feImage href="https://img.bagevent.com/resource/20210610/1714587612971445.png" result="7CA83715-60E2-47AE-AD1F-D30D5C3E5B8D"/>
</filter>
Copy the code

As you may have noticed, there is a discrepancy between the href value in the screenshot and that in the code, which is baseURL, and that in the code is the URL of the HTTP request. Here I would like to explain that there is a pit in the example of making this primitive. When using SVG images to be imported in HTML through , if the URL of the image imported in SVG through the

primitive and the
element is from the network, the SVG display, No request is made for these external images, which results in the external images being displayed blank. Unless the URL of the image you are importing is a Data URL, the images imported from

and
will only work if SVG is inlined in HTML or displayed separately.

In this case, the upper-left thumbnail is an SVG image introduced with the < IMG > tag, so this happens. Because the base64 URL directly in this post is too long, the code here is the real URL of the image. The same below.

Imported via SVG, and external in SVG and images from the network request:

Open SVG alone:

<filter xmlns="http://www.w3.org/2000/svg" id="filter">
  <feImage href="https://img.bagevent.com/resource/20210610/1714587612971445.png" result="0A0CDDF8-24B3-40A1-B04D-A581C8A5D1C4"/>
</filter>
Copy the code

[example 2-6] will preserveAspectiveRatioalign part (the first value) is set to none:

At this point, the image is stretched to the full effect of the filter.

<filter xmlns="http://www.w3.org/2000/svg" id="filter">
  <feImage href="https://img.bagevent.com/resource/20210610/1714587612971445.png" preserveAspectRatio="none" result="0A0CDDF8-24B3-40A1-B04D-A581C8A5D1C4"/>
</filter>
Copy the code

PS: If you are careful enough, you will notice that the image content on the page is not fully displayed. If you rememberarticleWe mentioned the filter area concept, I believe you already know why ~

[example 2-6] will preserveAspectiveRatioalign part (the first value) is set to other values, to see in keeping the proportion of cases, was introduced here how image alignment.

Then preserveAspectiveRatiomeetOrSlice example 2-7 】 【 part (the second value) is set to slice, to see here was introduced to align after image beyond filter effect.

feTurbulence– Generate noise

This filter is mainly used to generate noise images that contain color and Alpha channels.

  • type

    Noise type

    Optional value of fractalNoise | turbulence

    FractalNoise and turbulence respectively represent classified noise and turbulent noise, which mainly represent two different noise generation algorithms.

This is the relevant code. The following example will modify it:

<filter id="filter1">
    <feTurbulence type="turbulence" baseFrequency="0.02" numOctaves="10" stitchTiles="stitch" seed="0.05" result="B90FB311-12A2-4CAF-AAC7-044B4D4F8043"/>
</filter>
<filter id="filter2">
    <feTurbulence type="fractalNoise" baseFrequency="0.02" numOctaves="10" stitchTiles="stitch" seed="0.05" result="B55AA3B1-8BAC-4260-944C-07FBEFCE37E3"/>
</filter>
Copy the code
  • baseFrequency

    The frequency of noise in the X and Y directions

    The value can be an integer or a decimal. It accepts 1 or 2 values

    If expressed in an easy-to-understand but inaccurate way, this value can refer to the scale of the noise. This is analogous to the definition of frequency of the sine function.

    The X and Y frequencies can be set separately. If one value is set, the X and Y frequencies are both the same value. If two values are set, the first value in the X direction and the second value in the Y direction are taken.

    In the case of turbulence, we set different baseFrequency values. On the left, there is a flattening sensation — doesn’t it look a bit like the ripples in a river? That’s probably why it’s translated as “turbulent noise.”

  • numOctaves

    Noise details

    Value as an integer

    Looking at other articles on the web, the general generalization of this value as the details of noise is an easy to understand but inaccurate statement. If this value is set low enough, the noise becomes blurred; The larger the value, the more detail the noise is generated; When this value is set to large enough, no more detail will be displayed due to the image resolution. As shown in the figure:

  • seed

    Random seeds for noise generation. As can be seen from the figure below, the noise generated by different numbers of seeds is also different.

    The value is a numeric value

  • stitchTiles

    Whether the resulting noise pattern is smooth and continuous when it is spread out in all directions (there seems to be a special term called “square continuous pattern”)

    Optional values including stitch, | noStitch, namely “continuous” and “discontinuous”, the default value is noStitch

    I’ve tried many times before and haven’t been able to see how this property works (I can’t imagine how the pattern should be sequentially arranged), except that the edges of the image may change slightly. I took a look at zhang Xinxu’s demo – it looks like multiple elements with this filter should be put together to see the effect.

    [example 2-7]

    So I tried a demo on CodePen that applied filters to multiple elements that were positioned using transform

    If stitchTiles = “noStitch” :

    It can be found that the convergence of noise patterns between elements is not smooth, and obvious seams can be seen. So, let’s adjust this property. StitchTiles =”stitch”;

    It’s almost impossible to see the seams.

    [example 2-8]

    It should be noted that each of these elements is positioned using a transform, not x or y. You can see another demo: apply the filter to multiple elements that use x and y to determine their positions

    As you can see from the figure, these elements all use the same filter, and the noise is continuous and uninterrupted. So you know that noise always starts at the upper left corner of the < SVG > element, not the upper left corner of the element to which the filter is applied. When the filter is applied to the lower element, the filter area is used to cut the noise wave, and the noise wave is taken within the filter area. In the example above [Example 2-7], since the x and Y attributes of the element to which the filter is applied are not set, they will remain 0, i.e. all elements are in the upper left corner of < SVG >, and the resulting crop is the noise of the same area. However, after the transform attribute is used to carry out the displacement transformation, the cutting area of the noise is still maintained. Therefore, multiple elements can be used to tile the same noise area in this way.


This article mainly introduces the content of the first step of SVG filter — the introduction of images. Just as the smart woman has rice, can make delicious rice, after we have the image source, the next process is naturally to process the image. Stay tuned for my next posts.


Total directory:

  1. CSS filter paper
  2. The overview article
  3. Image introduction