stroke-linecap 线帽

详细介绍SVG的stroke-linecap线帽属性,包括butt、round、square三种样式的区别和用法。通过实例掌握如何美化线条端点。 stroke-linecap属性定义开放路径端点的形状样式。

基本语法

<element stroke-linecap="样式值"/>

三种样式

butt(默认值)

线条端点平直,与路径端点对齐。

butt:端点与路径对齐
<line x1="50" y1="50" x2="250" y2="50" stroke="#3498db" stroke-width="20" stroke-linecap="butt"/>

round

线条端点为半圆形,向外延伸半个线宽。

round:半圆形端点
<line x1="50" y1="50" x2="250" y2="50" stroke="#3498db" stroke-width="20" stroke-linecap="round"/>

square

线条端点为方形,向外延伸半个线宽。

square:方形端点延伸
<line x1="50" y1="50" x2="250" y2="50" stroke="#3498db" stroke-width="20" stroke-linecap="square"/>

三种样式对比

butt round square
<line x1="50" y1="40" x2="250" y2="40" stroke="#e74c3c" stroke-width="15" stroke-linecap="butt"/>
<line x1="50" y1="90" x2="250" y2="90" stroke="#3498db" stroke-width="15" stroke-linecap="round"/>
<line x1="50" y1="140" x2="250" y2="140" stroke="#2ecc71" stroke-width="15" stroke-linecap="square"/>

实际应用

图标设计

<line x1="40" y1="50" x2="80" y2="50" stroke="#3498db" stroke-width="8" stroke-linecap="round"/>
<line x1="60" y1="30" x2="60" y2="70" stroke="#3498db" stroke-width="8" stroke-linecap="round"/>

进度条

<line x1="20" y1="50" x2="180" y2="50" stroke="#ecf0f1" stroke-width="10" stroke-linecap="round"/>
<line x1="20" y1="50" x2="130" y2="50" stroke="#3498db" stroke-width="10" stroke-linecap="round"/>

连接线

<line x1="30" y1="30" x2="170" y2="70" stroke="#3498db" stroke-width="6" stroke-linecap="round"/>
<circle cx="30" cy="30" r="8" fill="#e74c3c"/>
<circle cx="170" cy="70" r="8" fill="#e74c3c"/>

注意事项

对闭合路径无效

stroke-linecap只对开放路径的端点有效,闭合路径没有端点。

闭合路径 闭合路径
<polygon points="60,20 100,80 20,80" fill="none" stroke="#3498db" stroke-width="8" stroke-linecap="round"/>

长度影响

round和square会使线条实际长度增加半个线宽。

<line x1="50" y1="30" x2="250" y2="30" stroke="#e74c3c" stroke-width="10" stroke-linecap="butt"/>
<line x1="50" y1="60" x2="250" y2="60" stroke="#3498db" stroke-width="10" stroke-linecap="round"/>
<line x1="50" y1="90" x2="250" y2="90" stroke="#2ecc71" stroke-width="10" stroke-linecap="square"/>