SVG 渐变
2025年2月7日大约 2 分钟
渐变是一种从一种颜色到另一种颜色的平滑过渡。
SVG 渐变主要有两种类型:
- 线性渐变:
<linearGradient>
- 径向渐变:
<radialGradient>
线性渐变
线性渐变: 沿着一条直线从一个颜色过渡到另一个颜色。
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="red" />
<stop offset="100%" stop-color="blue" />
</linearGradient>
<rect x="50" y="50" width="100" height="80" fill="url(#gradient)" />
</svg>
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="red" />
<stop offset="100%" stop-color="blue" />
</linearGradient>
<rect x="50" y="50" width="100" height="80" fill="url(#gradient)" />
</svg>
linearGradient
主要属性:
x1
: 渐变开始点的 x 坐标。y1
: 渐变开始点的 y 坐标。x2
: 渐变结束点的 x 坐标。y2
: 渐变结束点的 y 坐标。gradientUnits
: 渐变坐标单位。gradientTransform
: 渐变变换矩阵。
stop
主要属性:
offset
: 渐变颜色在渐变中的位置。stop-color
: 渐变颜色。
相关信息
线性渐变可以定义为水平,垂直或角渐变:
- 当 y1 和 y2 相等,而 x1 和 x2 不同时,可创建水平渐变。
- 当 x1 和 x2 相等,而 y1 和 y2 不同时,可创建垂直渐变。
- 当 x1 和 x2 不同,且 y1 和 y2 不同时,可创建角形渐变。
径向渐变
径向渐变: 从一个中心点向外扩散形成渐变效果。
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<radialGradient id="radialGradient" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
<stop offset="10%" stop-color="gold" />
<stop offset="95%" stop-color="red" />
</radialGradient>
<circle cx="100" cy="100" r="45" fill="url('#radialGradient')" />
</svg>
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<radialGradient id="radialGradient" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
<stop offset="10%" stop-color="gold" />
<stop offset="95%" stop-color="red" />
</radialGradient>
<circle cx="100" cy="100" r="45" fill="url('#radialGradient')" />
</svg>
radialGradient
主要属性:
cx
: 渐变中心点的 x 坐标。cy
: 渐变中心点的 y 坐标。r
: 渐变半径。fx
: 渐变焦点点的 x 坐标。fy
: 渐变焦点点的 y 坐标。gradientUnits
: 渐变坐标单位。gradientTransform
: 渐变变换矩阵。
stop
主要属性:
offset
: 渐变颜色在渐变中的位置。stop-color
: 渐变颜色。