SVG 线性渐变
<defs> 和 <filter>
所有 SVG 滤镜都在 <defs> 元素中定义。<defs> 元素是定义(definitions)的缩写,包含对特殊元素(比如滤镜)的定义。
<filter> 元素用于定义 SVG 滤镜。<filter> 元素有一个必需的 id 属性,用于标识滤镜。然后图形会指向要使用的滤镜。
SVG <feOffset>
例子 1
<feOffset> 元素用于创建阴影效果。思路是:首先获取一个 SVG 图形(图像或元素),然后在 xy 平面上稍微移动它。
第一个例子偏移了一个矩形(使用 <feOffset>),然后将原始图像混合到偏移图像的顶部(使用 <feBlend>):
这是 SVG 代码:
<svg height="120" width="120">
<defs>
<filter id="f1" x="0" y="0" width="200%" height="200%">
<feOffset result="offOut" in="SourceGraphic" dx="20" dy="20" />
<feBlend in="SourceGraphic" in2="offOut" mode="normal" />
</filter>
</defs>
<rect width="90" height="90" stroke="green" stroke-width="3"
fill="yellow" filter="url(#f1)" />
</svg>
代码解释:
- <filter> 元素的 id 属性定义了滤镜的唯一名称
- <rect> 元素的 filter 属性将该元素链接到 "f1" 滤镜
例子 2
现在,可以模糊偏移图像了(使用 <feGaussianBlur>):
这是 SVG 代码:
<svg height="140" width="140">
<defs>
<filter id="f2" x="0" y="0" width="200%" height="200%">
<feOffset result="offOut" in="SourceGraphic" dx="20" dy="20" />
<feGaussianBlur result="blurOut" in="offOut" stdDeviation="10" />
<feBlend in="SourceGraphic" in2="blurOut" mode="normal" />
</filter>
</defs>
<rect width="90" height="90" stroke="green" stroke-width="3"
fill="yellow" filter="url(#f2)" />
</svg>
代码解释:
- <feGaussianBlur> 元素的 stdDeviation 属性定义模糊量
例子 3
现在,将阴影设为黑色:
这是 SVG 代码:
<svg height="140" width="140">
<defs>
<filter id="f3" x="0" y="0" width="200%" height="200%">
<feOffset result="offOut" in="SourceAlpha" dx="20" dy="20" />
<feGaussianBlur result="blurOut" in="offOut" stdDeviation="10" />
<feBlend in="SourceGraphic" in2="blurOut" mode="normal" />
</filter>
</defs>
<rect width="90" height="90" stroke="green" stroke-width="3"
fill="yellow" filter="url(#f3)" />
</svg>
代码解释:
- <feOffset> 元素的 in 属性被更改为 "SourceAlpha",它使用 Alpha 通道而不是整个 RGBA 像素进行模糊
例子 4
现在,将阴影处理为一种颜色:
这是 SVG 代码:
<svg height="140" width="140">
<defs>
<filter id="f4" x="0" y="0" width="200%" height="200%">
<feOffset result="offOut" in="SourceGraphic" dx="20" dy="20" />
<feColorMatrix result="matrixOut" in="offOut" type="matrix"
values="0.2 0 0 0 0 0 0.2 0 0 0 0 0 0.2 0 0 0 0 0 1 0" />
<feGaussianBlur result="blurOut" in="matrixOut" stdDeviation="10" />
<feBlend in="SourceGraphic" in2="blurOut" mode="normal" />
</filter>
</defs>
<rect width="90" height="90" stroke="green" stroke-width="3"
fill="yellow" filter="url(#f4)" />
</svg>
代码解释:
- <feColorMatrix> 滤镜用于将偏移图像中的颜色转换为更接近黑色。矩阵中的三个 '0.2' 值都乘以红色、绿色和蓝色通道。减少它们的值会使颜色更接近黑色(黑色为 0)