全面介绍SVG渐变与图案技术,包括线性渐变、径向渐变和图案填充。掌握创建丰富视觉效果的核心技术。 渐变和图案是SVG中创建丰富视觉效果的重要手段,可以实现从简单颜色过渡到复杂纹理的各种效果。
SVG支持两种渐变类型:
| 类型 | 元素 | 说明 |
|---|---|---|
| 线性渐变 | linearGradient | 沿直线方向的颜色过渡 |
| 径向渐变 | radialGradient | 从中心向外辐射的颜色过渡 |
渐变需要定义在defs元素中,然后通过ID引用。
<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)"/>
| 场景 | 推荐技术 |
|---|---|
| 按钮背景 | 线性渐变 |
| 球体效果 | 径向渐变 |
| 背景纹理 | 图案填充 |
| 进度条 | 线性渐变 |
| 图标装饰 | 渐变+图案 |