SVG支持线性渐变和径向渐变,这使得我们能够创建平滑的颜色过渡效果。
线性渐变
线性渐变(linearGradient
)沿着一条直线逐渐变化颜色。你可以定义渐变的起点和终点,以及沿着这条线的颜色变化。
示例代码
<svg width="300" height="100">
<!-- 定义一个径向渐变 -->
<defs>
<linearGradient
id="linear-gradient-v"
x1="0%"
y1="0%"
x2="100%"
y2="0%"
>
<stop
offset="0%"
style="stop-color: rgb(255, 255, 0); stop-opacity: 1"
/>
<stop
offset="100%"
style="stop-color: rgb(255, 0, 0); stop-opacity: 1"
/>
</linearGradient>
<linearGradient
id="linear-gradient-h"
x1="0%"
y1="0%"
x2="0%"
y2="100%"
>
<stop
offset="0%"
style="stop-color: rgb(255, 255, 0); stop-opacity: 1"
/>
<stop
offset="100%"
style="stop-color: rgb(255, 0, 0); stop-opacity: 1"
/>
</linearGradient>
</defs>
<!-- 应用渐变到圆形 -->
<rect
x="10"
y="10"
width="100"
height="100"
fill="url(#linear-gradient-v)"
/>
<rect
x="150"
y="10"
width="100"
height="100"
fill="url(#linear-gradient-h)"
/>
</svg>
在这个例子中,<linearGradient>
分别定义了一个从左到右、从上到下的 黄色到红色的渐变。<stop>
元素定义了渐变中的颜色节点,offset
属性指定了颜色变化的位置。
径向渐变
径向渐变(radialGradient
)从一个点向外逐渐变化颜色。你可以定义渐变的中心点、半径,以及颜色变化。
示例代码
<svg width="200" height="200">
<!-- 定义一个径向渐变 -->
<defs>
<radialGradient
id="radial-gradient-i"
cx="50%"
cy="50%"
r="50%"
fx="50%"
fy="50%"
>
<stop
offset="0%"
style="stop-color: rgb(0, 255, 0); stop-opacity: 1"
/>
<stop
offset="100%"
style="stop-color: rgb(0, 0, 255); stop-opacity: 1"
/>
</radialGradient>
<radialGradient
id="radial-gradient-o"
cx="50%"
cy="50%"
r="50%"
fx="50%"
fy="50%"
>
<stop
offset="0%"
style="stop-color: rgb(255, 0, 0); stop-opacity: 1"
/>
<stop
offset="50%"
style="stop-color: rgb(0, 255, 0); stop-opacity: 1"
/>
<stop
offset="100%"
style="stop-color: rgb(0, 0, 255); stop-opacity: 1"
/>
</radialGradient>
</defs>
<!-- 应用渐变到圆形 -->
<circle cx="50" cy="50" r="40" fill="url(#radial-gradient-i)" />
<circle cx="150" cy="50" r="40" fill="url(#radial-gradient-o)" />
</svg>
在这个例子中,<radialGradient>
定义了一个从中心向外的绿色到蓝色的渐变。cx
和 cy
属性定义了渐变的中心点,r
属性定义了渐变的半径。
说明
- 渐变定义在
<defs>
元素内,可以被多个图形元素引用。 id
属性用于在图形元素中通过fill
属性引用渐变。stop-color
定义了停止点的颜色,stop-opacity
定义了颜色的透明度。
好的,下一节我们继续深入了解SVG渐变中的spreadMethod
和gradientUnits
属性。