<filter>
The <filter>
tag is used in an SVG document to apply graphical effects, such as blurs, drop shadows, or color blending, to SVG elements (not with the <svg>
tag).
It serves as a container for various filter effects, allowing you to apply complex visual effects to your SVG elements.
Use
<filter>
to centralize reusable filters in your SVG. Simplification! 😊
Structure and syntax of the <filter>
tag
Structure
Here is a basic example of syntax:
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<defs>
<filter id="blurFilter">
<feGaussianBlur in="SourceGraphic" stdDeviation="5" />
</filter>
</defs>
<circle cx="100" cy="100" r="50" fill="blue" filter="url(#blurFilter)" />
</svg>
In this example:
- A filter (
<filter>
) is defined within<defs>
with anid
(#blurFilter
); - The filter is then applied to the circle using
filter="url(#blurFilter)"
.
Here is the result of this example:
Example
Here is an example using multiple filters to create a drop shadow effect:
<svg width="300" height="200" xmlns="http://www.w3.org/2000/svg">
<defs>
<filter id="dropShadow">
<feOffset dx="5" dy="5" result="offset" />
<feGaussianBlur in="offset" stdDeviation="3" result="blur" />
<feBlend in="SourceGraphic" in2="blur" mode="normal" />
</filter>
</defs>
<text x="50" y="100" font-size="40" fill="black" filter="url(#dropShadow)">
Shadowed Text
</text>
</svg>
In this example:
<feOffset>
offsets the text to create the shadow effect.<feGaussianBlur>
blurs the shadow.<feBlend>
combines the original text with the blurred shadow.
Here is the result:
Attributes of the <filter>
tag
The <filter>
tag accepts several attributes to customize its behavior:
Attribute | Description |
---|---|
id | Unique identifier to reference the filter. |
x , y | Position of the filter relative to the object (default is -10% ). |
width , height | Dimensions of the filter. By default, they include the visual effects in the object's bounds. |
filterUnits | Units for dimensions (userSpaceOnUse or objectBoundingBox ). |
primitiveUnits | Units for internal primitives (userSpaceOnUse or objectBoundingBox ). |
Best practices
Here are some tips for effectively using <filter>
:
- Always place your filters in a
<defs>
container to centralize their definition (your code will be simpler). - Use clear and meaningful
id
s for the filters defined. - Combine
<filter>
with CSS attributes or transformations to efficiently reuse graphical resources.
For advanced usage, combine
<filter>
with other tags like<use>
to create reusable groups.
Browser compatibility
The <filter>
tag is supported by all modern browsers:
Browser | Compatibility |
---|---|
Chrome | Yes |
Firefox | Yes |
Safari | Yes |
Edge | Yes |
Internet Explorer | Partial (IE 9+) |