{T}

样式与效果

SVG 提供丰富的样式属性,用于控制图形的外观,包括填充、描边、渐变、图案等。

填充属性

fill

设置形状内部填充颜色。

xml
<rect fill="red"/>
<rect fill="#ff0000"/>
<rect fill="rgb(255,0,0)"/>
<rect fill="rgba(255,0,0,0.5)"/>

fill-opacity

设置填充透明度。

xml
<rect fill="red" fill-opacity="0.5"/>

fill-rule

定义填充规则。

xml
<polygon points="..." fill-rule="evenodd"/>

描边属性

stroke

设置描边颜色。

xml
<rect stroke="black"/>

stroke-width

设置描边宽度。

xml
<rect stroke="black" stroke-width="2"/>

stroke-linecap

设置线条端点样式。

xml
<line stroke-linecap="round"/>

stroke-linejoin

设置线条连接处样式。

xml
<polygon stroke-linejoin="round"/>

stroke-dasharray

设置虚线模式。

xml
<line stroke-dasharray="5,5"/>

渐变

线性渐变

html
<svg>
  <defs>
    <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
      <stop offset="0%" stop-color="red"/>
      <stop offset="100%" stop-color="blue"/>
    </linearGradient>
  </defs>
  <rect fill="url(#grad1)"/>
</svg>

径向渐变

html
<svg>
  <defs>
    <radialGradient id="grad2" cx="50%" cy="50%" r="50%">
      <stop offset="0%" stop-color="yellow"/>
      <stop offset="100%" stop-color="red"/>
    </radialGradient>
  </defs>
  <circle fill="url(#grad2)"/>
</svg>

图案

html
<svg>
  <defs>
    <pattern id="patt1" x="0" y="0" width="20" height="20">
      <circle cx="10" cy="10" r="5" fill="blue"/>
    </pattern>
  </defs>
  <rect fill="url(#patt1)"/>
</svg>

透明度

opacity

设置整体透明度。

xml
<rect opacity="0.5"/>

fill-opacity 和 stroke-opacity

分别设置填充和描边的透明度。

xml
<rect fill="red" fill-opacity="0.5" stroke="black" stroke-opacity="0.7"/>

CSS 样式

SVG 支持 CSS 样式,可以使用内联样式、内部样式表或外部样式表。

内联样式

xml
<rect style="fill: red; stroke: black;"/>

内部样式表

xml
<svg>
  <style>
    .my-rect {
      fill: blue;
      stroke: black;
    }
  </style>
  <rect class="my-rect"/>
</svg>

参考资源