渐变与图案

全面介绍SVG渐变与图案技术,包括线性渐变、径向渐变和图案填充。掌握创建丰富视觉效果的核心技术。 渐变和图案是SVG中创建丰富视觉效果的重要手段,可以实现从简单颜色过渡到复杂纹理的各种效果。

渐变类型

SVG支持两种渐变类型:

类型元素说明
线性渐变linearGradient沿直线方向的颜色过渡
径向渐变radialGradient从中心向外辐射的颜色过渡

基本结构

渐变需要定义在defs元素中,然后通过ID引用。

<text x="80" y="130" text-anchor="middle" font-size="10" fill="#666">线性渐变</text>
<text x="200" y="130" text-anchor="middle" font-size="10" fill="#666">径向渐变</text>
<defs>
  <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
    <stop offset="0%" style="stop-color:#3498db"/>
    <stop offset="100%" style="stop-color:#e74c3c"/>
  </linearGradient>
  <radialGradient id="grad2" cx="50%" cy="50%" r="50%">
    <stop offset="0%" style="stop-color:#f39c12"/>
    <stop offset="100%" style="stop-color:#e74c3c"/>
  </radialGradient>
</defs>

<rect x="30" y="30" width="100" height="80" fill="url(#grad1)"/>
<circle cx="200" cy="70" r="45" fill="url(#grad2)"/>

图案填充

pattern元素可以创建重复的图案作为填充内容。

圆点图案 方格图案
<defs>
  <pattern id="pattern1" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse">
    <circle cx="10" cy="10" r="5" fill="#3498db" opacity="0.5"/>
  </pattern>
  <pattern id="pattern2" x="0" y="0" width="15" height="15" patternUnits="userSpaceOnUse">
    <rect x="0" y="0" width="7" height="7" fill="#e74c3c" opacity="0.3"/>
    <rect x="8" y="8" width="7" height="7" fill="#e74c3c" opacity="0.3"/>
  </pattern>
</defs>

<rect x="30" y="30" width="100" height="80" fill="url(#pattern1)"/>
<rect x="170" y="30" width="100" height="80" fill="url(#pattern2)"/>

渐变与图案组合

渐变和图案可以组合使用,创造更丰富的效果。

渐变+图案
<defs>
  <linearGradient id="grad3" x1="0%" y1="0%" x2="0%" y2="100%">
    <stop offset="0%" style="stop-color:#3498db"/>
    <stop offset="100%" style="stop-color:#2ecc71"/>
  </linearGradient>
  <pattern id="pattern3" x="0" y="0" width="10" height="10" patternUnits="userSpaceOnUse">
    <line x1="0" y="0" x2="10" y2="10" stroke="#fff" stroke-width="1" opacity="0.3"/>
  </pattern>
</defs>

<rect x="30" y="30" width="240" height="80" fill="url(#grad3)"/>
<rect x="30" y="30" width="240" height="80" fill="url(#pattern3)"/>

应用场景

场景推荐技术
按钮背景线性渐变
球体效果径向渐变
背景纹理图案填充
进度条线性渐变
图标装饰渐变+图案