全面介绍SVG图形的填充与描边属性,包括fill填充、stroke描边、线宽、线帽、线连接等样式设置。掌握SVG图形外观控制的核心技术。
填充和描边是SVG图形的两个基本视觉属性,决定了图形的内部颜色和轮廓样式。
<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"/>
<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"/>
<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图形的基础样式: