Skip to content

SVG 线性渐变

渐变(Gradients)用于创建平滑的颜色过渡。SVG 支持两种主要的渐变类型:

  • **线性渐变(<linearGradient>):**颜色沿直线过渡。
  • **径向渐变(<radialGradient>):**颜色从中心点向四周呈径向过渡。

本章重点介绍线性渐变。

<linearGradient> 元素用于定义线性渐变。它必须放置在 <defs>(定义)部分中。<defs> 元素用于存放可复用的 SVG 定义。

线性渐变由一个矢量 (x1, y1) 到 (x2, y2) 定义。

  • 水平渐变: y1 等于 y2;x1 与 x2 不同。
  • 垂直渐变: x1 等于 x2;y1 与 y2 不同。
  • 角度渐变: x1, x2 和 y1, y2 都不同。

gradientUnits 属性(userSpaceOnUse 或 objectBoundingBox)决定渐变坐标是绝对的还是相对于对象的边界框(默认值)的。

将水平渐变(从黄色到红色)应用于一个椭圆:

一个椭圆,填充了从左侧黄色过渡到右侧红色的水平渐变。

SVG 代码:

<svg width="400" height="150">
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:yellow; stop-opacity:1;" />
<stop offset="100%" style="stop-color:red; stop-opacity:1;" />
</linearGradient>
</defs>
<ellipse cx="200" cy="70" rx="85" ry="55" fill="url(#grad1)" />
</svg>

代码解释:

  • <linearGradient id=“grad1”>:定义渐变,并为其指定唯一的 ID。
  • x1, y1, x2, y2:定义渐变矢量。这里表示水平方向从 0% 到 100%。
  • <stop> 元素:定义渐变中的颜色停止点。
  • offset:颜色停止点的位置(0% 到 100% 或 0 到 1)。
  • style=“stop-color:color; stop-opacity:value;“:设置停止点的颜色和不透明度。
  • fill=“url(#grad1)“:将渐变应用于椭圆的填充。

将垂直渐变(从黄色到红色)应用于一个椭圆:

一个椭圆,填充了从顶部黄色过渡到底部红色的垂直渐变。

SVG 代码:

<svg width="400" height="150">
<defs>
<linearGradient id="grad2" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" style="stop-color:yellow; stop-opacity:1;" />
<stop offset="100%" style="stop-color:red; stop-opacity:1;" />
</linearGradient>
</defs>
<ellipse cx="200" cy="70" rx="85" ry="55" fill="url(#grad2)" />
</svg>

注意:与示例 1 唯一的区别在于 <linearGradient> 中:x2 为 0%,y2 为 100%,从而创建了垂直方向的路径。

一个带水平渐变的椭圆,并在其上叠加文本:

一个带有黄色到红色水平渐变的椭圆,并在其中心叠加了白色的文本 “SVG”。

SVG 代码:

<svg width="400" height="150">
<defs>
<linearGradient id="grad3" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:yellow; stop-opacity:1;" />
<stop offset="100%" style="stop-color:red; stop-opacity:1;" />
</linearGradient>
</defs>
<ellipse cx="200" cy="70" rx="85" ry="55" fill="url(#grad3)" />
<text x="155" y="86" fill="#ffffff" font-family="Verdana, sans-serif" font-size="45">
SVG
</text>
</svg>

代码解释:

  • <text> 元素在椭圆之后添加。SVG 元素按照它们在文档中出现的顺序进行渲染。
  • 文本通过 fill、font-family 和 font-size 进行样式设置。

线性渐变广泛用于背景、按钮、图表柱、进度条,以及为任何 SVG 元素增加深度或视觉趣味。您可以使用两个以上的停止点来创建多色渐变。

有关更复杂的渐变变换(transformations)或扩散方法(spread methods),请参阅 MDN Web Docs 上的 SVG 规范。