Dần đổi tuyến tính SVG

<defs> 和 <filter>

所有 SVG 滤镜都在 <defs> 元素中定义。<defs> 元素是定义(definitions)的缩写,包含对特殊元素(比如滤镜)的定义。

<filter> 元素用于定义 SVG 滤镜。<filter> 元素有一个必需的 id 属性,用于标识滤镜。然后图形会指向要使用的滤镜。

SVG <feOffset>

例子 1

<feOffset> 元素用于创建阴影效果。思路是:首先获取一个 SVG 图形(图像或元素),然后在 xy 平面上稍微移动它。

第一个例子偏移了一个矩形(使用 <feOffset>),然后将原始图像混合到偏移图像的顶部(使用 <feBlend>):

Đây là mã 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>

Thử trực tiếp

Giải thích mã:

  • <filter> 元素的 id 属性定义了滤镜的唯一名称
  • <rect> 元素的 filter 属性将该元素链接到 "f1" 滤镜

例子 2

现在,可以模糊偏移图像了(使用 <feGaussianBlur>):

Đây là mã 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>

Thử trực tiếp

Giải thích mã:

  • <feGaussianBlur> 元素的 stdDeviation 属性定义模糊量

Ví dụ 3

Bây giờ, đặt bóng thành đen:

Đây là mã 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>

Thử trực tiếp

Giải thích mã:

  • Thiết lập thuộc tính in của phần tử <feOffset> thành "SourceAlpha", nó sử dụng kênh Alpha thay vì pixel RGBA toàn bộ để mờ

Ví dụ 4

Bây giờ, xử lý bóng bằng một màu:

Đây là mã 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>

Thử trực tiếp

Giải thích mã:

  • <feColorMatrix> bộ lọc được sử dụng để chuyển đổi màu sắc của hình ảnh dịch chuyển để gần với đen hơn. Ba giá trị '0.2' trong ma trận đều nhân với kênh đỏ, xanh và xanh dương. Giảm giá trị của chúng sẽ làm cho màu sắc gần với đen hơn (đen là 0)