扩展方法

spreadMethod 属性决定了当渐变超出定义的渐变边缘时,形状的填充方式。

你可以将此属性与以下 SVG 元素一起使用

用法说明

pad | reflect | repeat
初始值 pad
可动画的
pad

此值表示渐变的最终颜色会填充到渐变边缘之外的形状区域。

reflect

此值表示渐变在超出其边缘后会反向重复。

repeat

此值指定渐变在超出其边缘后会按照原始顺序重复。

定义渐变的边缘

默认情况下,渐变会延伸到被填充形状的边缘。要看到此属性的效果,您需要将渐变的大小设置为小于形状。

对于线性渐变,可以通过 x1x2y1y2 属性将边缘定义为矩形。对于径向渐变,可以通过 cxcyr(外圆)以及 fxfyfr(内圆)属性将边缘定义为外圆和内圆。

线性渐变的 spreadMethod 示例

SVG

html
<svg width="220" height="150" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <linearGradient id="PadGradient" x1="33%" x2="67%">
      <stop offset="0%" stop-color="fuchsia" />
      <stop offset="100%" stop-color="orange" />
    </linearGradient>
    <linearGradient
      id="ReflectGradient"
      spreadMethod="reflect"
      x1="33%"
      x2="67%">
      <stop offset="0%" stop-color="fuchsia" />
      <stop offset="100%" stop-color="orange" />
    </linearGradient>
    <linearGradient id="RepeatGradient" spreadMethod="repeat" x1="33%" x2="67%">
      <stop offset="0%" stop-color="fuchsia" />
      <stop offset="100%" stop-color="orange" />
    </linearGradient>
  </defs>

  <rect fill="url(#PadGradient)" x="10" y="0" width="200" height="40" />
  <rect fill="url(#ReflectGradient)" x="10" y="50" width="200" height="40" />
  <rect fill="url(#RepeatGradient)" x="10" y="100" width="200" height="40" />
</svg>

结果

请注意,每个渐变的中三分之一是相同的。外三分之一显示了三种 spreadMethod 之间的区别。

径向渐变的 spreadMethod 示例

SVG

html
<svg width="340" height="120" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <radialGradient
      id="RadialPadGradient"
      cx="75%"
      cy="25%"
      r="33%"
      fx="64%"
      fy="18%"
      fr="17%">
      <stop offset="0%" stop-color="fuchsia" />
      <stop offset="100%" stop-color="orange" />
    </radialGradient>
    <radialGradient
      id="RadialReflectGradient"
      spreadMethod="reflect"
      cx="75%"
      cy="25%"
      r="33%"
      fx="64%"
      fy="18%"
      fr="17%">
      <stop offset="0%" stop-color="fuchsia" />
      <stop offset="100%" stop-color="orange" />
    </radialGradient>
    <radialGradient
      id="RadialRepeatGradient"
      spreadMethod="repeat"
      cx="75%"
      cy="25%"
      r="33%"
      fx="64%"
      fy="18%"
      fr="17%">
      <stop offset="0%" stop-color="fuchsia" />
      <stop offset="100%" stop-color="orange" />
    </radialGradient>
  </defs>

  <rect fill="url(#RadialPadGradient)" x="10" y="10" width="100" height="100" />
  <rect
    fill="url(#RadialReflectGradient)"
    x="120"
    y="10"
    width="100"
    height="100" />
  <rect
    fill="url(#RadialRepeatGradient)"
    x="230"
    y="10"
    width="100"
    height="100" />
</svg>

结果

规范

规范
Scalable Vector Graphics (SVG) 2
# LinearGradientElementSpreadMethodAttribute
Scalable Vector Graphics (SVG) 2
# RadialGradientElementSpreadMethodAttribute

浏览器兼容性

svg.elements.linearGradient.spreadMethod

svg.elements.radialGradient.spreadMethod