线性渐变和径向渐变都需要一些额外的属性用于描述渐变过程。下面有两个常用属性进一步控制渐变的行为细节。
spreadMethod
属性
spreadMethod
属性决定了渐变在起点和终点之外的区域如何展现。这个属性对于线性渐变和径向渐变都适用,它有三个可能的值:
pad
:默认值。渐变会在终点之后延伸最后一个颜色,直到图形的边界。repeat
:渐变会在终点之后重复整个渐变模式。reflect
:渐变会在终点之后以镜像的方式重复渐变模式。
示例代码
<svg width="400" height="200">
<!-- 定义一个线性渐变 -->
<defs>
<linearGradient
id="gradient-spread-reflect"
x1="0%"
y1="0%"
x2="50%"
y2="0%"
spreadMethod="reflect"
>
<stop
offset="0%"
style="stop-color: rgb(255, 255, 0); stop-opacity: 1"
/>
<stop
offset="50%"
style="stop-color: rgb(255, 0, 0); stop-opacity: 1"
/>
</linearGradient>
<linearGradient
id="gradient-spread-pad"
x1="0%"
y1="0%"
x2="50%"
y2="0%"
spreadMethod="pad"
>
<stop
offset="0%"
style="stop-color: rgb(255, 255, 0); stop-opacity: 1"
/>
<stop
offset="50%"
style="stop-color: rgb(255, 0, 0); stop-opacity: 1"
/>
</linearGradient>
<linearGradient
id="gradient-spread-repeat"
x1="0%"
y1="0%"
x2="50%"
y2="0%"
spreadMethod="repeat"
>
<stop
offset="0%"
style="stop-color: rgb(255, 255, 0); stop-opacity: 1"
/>
<stop
offset="50%"
style="stop-color: rgb(255, 0, 0); stop-opacity: 1"
/>
</linearGradient>
</defs>
<!-- 应用渐变到矩形 -->
<rect
x="10"
y="10"
width="100"
height="100"
fill="url(#gradient-spread-reflect)"
/>
<rect
x="130"
y="10"
width="100"
height="100"
fill="url(#gradient-spread-pad)"
/>
<rect
x="250"
y="10"
width="100"
height="100"
fill="url(#gradient-spread-repeat)"
/>
</svg>
在这个例子中,spreadMethod
设置为reflect
,pad
, repeat
,渐变在终点之后以镜像的方式,填充,反复的方式重复。
gradientUnits
属性
gradientUnits
属性用于定义渐变的坐标系统。它有两个可能的值:
userSpaceOnUse
:渐变的坐标系统与SVG画布的坐标系统相同。这意味着渐变的尺寸和位置是相对于整个SVG画布来定义的。objectBoundingBox
:渐变的坐标系统是相对于使用渐变的元素的边界框来定义的。这意味着渐变的尺寸和位置是相对于元素自身的。
使用场景
- 当你希望渐变效果与元素的大小无关,始终保持一致时,使用
userSpaceOnUse
。 - 当你希望渐变效果随元素的大小变化而变化时,使用
objectBoundingBox
。
示例代码
<svg width="200" height="200">
<!-- 定义一个线性渐变,使用SVG画布坐标系统 -->
<defs>
<linearGradient id="gradient-user-space" x1="0%" y1="0%" x2="100%" y2="0%" gradientUnits="userSpaceOnUse">
<stop offset="0%" style="stop-color:rgb(255,0,0); stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(0,0,255); stop-opacity:1" />
</linearGradient>
</defs>
<!-- 应用渐变到矩形 -->
<rect x="10" y="10" width="180" height="180" fill="url(#gradient-user-space)" />
</svg>
在这个例子中,gradientUnits
设置为userSpaceOnUse
,渐变的尺寸和位置是相对于整个SVG画布定义的,不管元素的大小如何变化,渐变效果都保持不变。
<svg width="200" height="200">
<!-- 定义一个线性渐变,使用元素的边界框坐标系统 -->
<defs>
<linearGradient id="gradient-bounding-box" x1="0%" y1="0%" x2="100%" y2="0%" gradientUnits="objectBoundingBox">
<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" />
</linearGradient>
</defs>
<!-- 应用渐变到矩形 -->
<rect x="50" y="50" width="100" height="100" fill="url(#gradient-bounding-box)" />
</svg>
在这个例子中,gradientUnits
设置为objectBoundingBox
,渐变的尺寸和位置是相对于矩形的边界框定义的,渐变效果会随着元素的大小变化而变化。