fill 填充属性

详细介绍SVG的fill填充属性,包括颜色值设置、透明度控制、渐变填充和图案填充。通过实例掌握各种填充技巧。 fill属性定义图形内部的填充内容,可以是纯色、渐变或图案。

基本语法

<element fill="颜色值"/>

颜色格式

十六进制

<rect x="20" y="20" width="70" height="60" fill="#e74c3c"/>
<rect x="115" y="20" width="70" height="60" fill="#3498db"/>
<rect x="210" y="20" width="70" height="60" fill="#2ecc71"/>

RGB/RGBA

<rect x="20" y="20" width="70" height="60" fill="rgb(231, 76, 60)"/>
<rect x="115" y="20" width="70" height="60" fill="rgb(52, 152, 219)"/>
<rect x="210" y="20" width="70" height="60" fill="rgba(46, 204, 113, 0.5)"/>

颜色名称

<rect x="20" y="20" width="70" height="60" fill="red"/>
<rect x="115" y="20" width="70" height="60" fill="blue"/>
<rect x="210" y="20" width="70" height="60" fill="green"/>

HSL/HSLA

<rect x="20" y="20" width="70" height="60" fill="hsl(0, 80%, 60%)"/>
<rect x="115" y="20" width="70" height="60" fill="hsl(200, 80%, 60%)"/>
<rect x="210" y="20" width="70" height="60" fill="hsla(120, 80%, 60%, 0.5)"/>

特殊值

none(无填充)

<circle cx="100" cy="50" r="40" fill="none" stroke="#3498db" stroke-width="3"/>

currentColor(当前颜色)

使用元素的color属性值作为填充色。

<svg style="color: #e74c3c;">
  <circle cx="100" cy="50" r="40" fill="currentColor"/>
</svg>

fill-opacity 填充透明度

单独控制填充的透明度,不影响描边。

opacity: 1 opacity: 0.5 opacity: 0.2
<rect x="20" y="20" width="70" height="60" fill="#3498db" fill-opacity="1"/>
<rect x="115" y="20" width="70" height="60" fill="#3498db" fill-opacity="0.5"/>
<rect x="210" y="20" width="70" height="60" fill="#3498db" fill-opacity="0.2"/>

渐变填充

线性渐变

<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>
</defs>
<rect x="20" y="20" width="160" height="60" fill="url(#grad1)"/>

径向渐变

<defs>
  <radialGradient id="grad2">
    <stop offset="0%" style="stop-color:#f1c40f"/>
    <stop offset="100%" style="stop-color:#e74c3c"/>
  </radialGradient>
</defs>
<circle cx="100" cy="50" r="40" fill="url(#grad2)"/>

图案填充

<defs>
  <pattern id="pattern1" patternUnits="userSpaceOnUse" width="10" height="10">
    <circle cx="5" cy="5" r="2" fill="#3498db"/>
  </pattern>
</defs>
<rect x="20" y="20" width="160" height="60" fill="url(#pattern1)"/>

实际应用

半透明叠加

<circle cx="70" cy="75" r="50" fill="#3498db" fill-opacity="0.7"/>
<circle cx="130" cy="75" r="50" fill="#e74c3c" fill-opacity="0.7"/>

卡片背景

渐变卡片
<defs>
  <linearGradient id="cardGrad" x1="0%" y1="0%" x2="100%" y2="100%">
    <stop offset="0%" style="stop-color:#667eea"/>
    <stop offset="100%" style="stop-color:#764ba2"/>
  </linearGradient>
</defs>
<rect x="20" y="20" width="160" height="80" rx="10" fill="url(#cardGrad)"/>
<text x="100" y="65" text-anchor="middle" font-size="14" fill="#fff">渐变卡片</text>