填充与描边

全面介绍SVG图形的填充与描边属性,包括fill填充、stroke描边、线宽、线帽、线连接等样式设置。掌握SVG图形外观控制的核心技术。

填充和描边是SVG图形的两个基本视觉属性,决定了图形的内部颜色和轮廓样式。

基本概念

  • 填充(fill):图形内部的颜色或图案
  • 描边(stroke):图形轮廓的线条
填充+描边 仅描边
<rect x="30" y="30" width="100" height="90" fill="#3498db" stroke="#2980b9" stroke-width="3"/>
<rect x="170" y="30" width="100" height="90" fill="none" stroke="#e74c3c" stroke-width="3"/>

属性概览

填充相关

属性说明默认值
fill填充颜色black
fill-opacity填充透明度1
fill-rule填充规则nonzero

描边相关

属性说明默认值
stroke描边颜色none
stroke-width描边宽度1
stroke-opacity描边透明度1
stroke-linecap线帽样式butt
stroke-linejoin线连接样式miter
stroke-dasharray虚线模式none
stroke-dashoffset虚线偏移0

填充颜色

纯色填充

<circle cx="60" cy="50" r="40" fill="#e74c3c"/>
<circle cx="150" cy="50" r="40" fill="rgb(46, 204, 113)"/>
<circle cx="240" cy="50" r="40" fill="rgba(52, 152, 219, 0.7)"/>

无填充

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

描边颜色

<rect x="30" y="20" width="60" height="60" fill="#ecf0f1" stroke="#e74c3c" stroke-width="3"/>
<rect x="120" y="20" width="60" height="60" fill="#ecf0f1" stroke="#3498db" stroke-width="3"/>
<rect x="210" y="20" width="60" height="60" fill="#ecf0f1" stroke="#2ecc71" stroke-width="3"/>

描边宽度

1px 5px 10px
<line x1="30" y1="50" x2="90" y2="50" stroke="#3498db" stroke-width="1"/>
<line x1="120" y1="50" x2="180" y2="50" stroke="#3498db" stroke-width="5"/>
<line x1="210" y1="50" x2="270" y2="50" stroke="#3498db" stroke-width="10"/>

组合使用

不同填充描边组合

仅填充 填充+描边 仅描边 粗描边
<rect x="20" y="20" width="70" height="60" fill="#3498db" stroke="none"/>
<rect x="110" y="20" width="70" height="60" fill="#3498db" stroke="#2980b9" stroke-width="3"/>
<rect x="200" y="20" width="70" height="60" fill="none" stroke="#e74c3c" stroke-width="3"/>
<rect x="290" y="20" width="70" height="60" fill="#2ecc71" stroke="#27ae60" stroke-width="5"/>

CSS样式设置

行内样式

<circle cx="50" cy="50" r="30" style="fill: #3498db; stroke: #2980b9; stroke-width: 2;"/>

内部样式表

<svg>
  <style>
    .my-rect {
      fill: #e74c3c;
      stroke: #c0392b;
      stroke-width: 2;
    }
  </style>
  <rect class="my-rect" x="10" y="10" width="80" height="80"/>
</svg>

外部样式表

.my-circle {
  fill: #3498db;
  stroke: #2980b9;
  stroke-width: 3;
}

继承与覆盖

子元素可以继承父元素的填充和描边属性。

<g fill="#3498db" stroke="#2980b9" stroke-width="2">
  <circle cx="60" cy="75" r="40"/>
  <circle cx="140" cy="75" r="40" fill="#e74c3c"/>
</g>

实际应用

按钮样式

<rect x="20" y="30" width="80" height="40" rx="5" fill="#3498db" stroke="#2980b9" stroke-width="2"/>
<rect x="110" y="30" width="80" height="40" rx="5" fill="none" stroke="#3498db" stroke-width="2"/>
<rect x="200" y="30" width="80" height="40" rx="5" fill="#e74c3c" stroke="#c0392b" stroke-width="2"/>

图标设计

<circle cx="50" cy="50" r="30" fill="#f39c12" stroke="#e67e22" stroke-width="3"/>
<path d="M 50,30 L 55,45 L 70,45 L 58,55 L 63,70 L 50,60 L 37,70 L 42,55 L 30,45 L 45,45 Z" fill="#fff"/>

小结

填充与描边是SVG图形的基础样式:

  • fill控制图形内部颜色
  • stroke控制图形轮廓
  • 可以使用多种颜色格式
  • 支持CSS样式设置
  • 子元素可以继承和覆盖父元素样式