在 SVG 中,stroke
属性用于设置图形的描边颜色。它通常与路径、圆形、矩形、线条等图形元素一起使用,定义其轮廓颜色。通过此属性,你可以创建不同颜色、样式、宽度的边框效果,进而使图形更具视觉冲击力。
目录
基本语法
<svg width="200" height="200">
<circle cx="100" cy="100" r="50" stroke="black" stroke-width="5" fill="red" />
</svg>
stroke
:指定边框颜色,可以是颜色名称、HEX值、RGB值等。stroke-width
:指定边框的宽度,单位为像素(px)。fill
:指定图形内部的填充颜色。
属性详解
- stroke:边框颜色
stroke
用来定义图形的边框颜色,可以使用任何有效的 CSS 颜色值。- 例如,
stroke="black"
、stroke="red"
、stroke="#ff0000"
、stroke="rgb(255, 0, 0)"
等。
- 例如,
- stroke-width:边框宽度
stroke-width
用于定义边框的宽度,单位通常为像素(px)。- 例如,
stroke-width="2"
,定义边框宽度为2px。
- 例如,
- stroke-linecap:端点样式
stroke-linecap
属性用于定义路径端点的样式,可以取以下值:butt
:默认值,直角端点。round
:圆角端点。square
:方形端点。- 例如,
stroke-linecap="round"
可以让端点呈现圆形。
- stroke-linejoin:连接点样式
stroke-linejoin
定义了连接路径拐角处的样式:miter
:默认值,尖锐的连接角(成锐角)。round
:圆角连接。bevel
:斜角连接。- 例如,
stroke-linejoin="round"
会让连接点显示为圆形。
- stroke-dasharray:虚线样式
stroke-dasharray
属性用来设置虚线的样式,定义虚线的长度及间隔:- 例如,
stroke-dasharray="5,5"
让虚线的长度为5px,间隔为5px。
- 例如,
- stroke-dashoffset:虚线偏移量
stroke-dashoffset
设置虚线的起始位置,控制虚线的偏移。
- stroke-opacity:边框透明度
stroke-opacity
设置边框的透明度,取值范围从0
(完全透明)到1
(完全不透明)。- 例如,
stroke-opacity="0.5"
使边框变为50%的透明度。
- 例如,
常见用法
- 设置边框颜色与宽度
<svg width="200" height="200">
<rect x="50" y="50" width="100" height="100" stroke="blue" stroke-width="4" fill="yellow" />
</svg>
- 该示例设置了一个黄色的矩形,并为其添加了一个蓝色的边框,边框宽度为4px。
- 虚线边框
<svg width="200" height="200">
<circle cx="100" cy="100" r="50" stroke="green" stroke-width="4" stroke-dasharray="5,5" fill="none" />
</svg>
- 这个例子中,圆形的边框被设置为绿色,并且采用了虚线效果,虚线的长度和间隔都是5px。
- 圆角端点
<svg width="200" height="200">
<line x1="10" y1="10" x2="190" y2="10" stroke="red" stroke-width="5" stroke-linecap="round" />
</svg>
- 这条线的端点呈现圆形效果,因为我们使用了
stroke-linecap="round"
属性。
- 斜角连接
<svg width="200" height="200">
<polyline points="10,10 190,10 190,190" stroke="purple" stroke-width="5" stroke-linejoin="bevel" fill="none" />
</svg>
- 这个示例展示了如何为多段线设置斜角连接,路径的拐角会呈现为斜角。
- 设置透明度
<svg width="200" height="200">
<rect x="50" y="50" width="100" height="100" stroke="black" stroke-width="5" stroke-opacity="0.5" fill="red" />
</svg>
- 这个例子中,矩形的边框颜色为黑色,边框宽度为5px,同时边框的透明度被设置为50%。
示例代码
- 黑色边框的矩形
<svg width="200" height="200">
<rect x="50" y="50" width="100" height="100" stroke="black" stroke-width="4" fill="yellow" />
</svg>
- 绿色虚线圆形
<svg width="200" height="200">
<circle cx="100" cy="100" r="50" stroke="green" stroke-width="4" stroke-dasharray="5,5" fill="none" />
</svg>
- 圆角端点的线条
<svg width="200" height="200">
<line x1="10" y1="10" x2="190" y2="10" stroke="red" stroke-width="5" stroke-linecap="round" />
</svg>
- 斜角连接的多段线
<svg width="200" height="200">
<polyline points="10,10 190,10 190,190" stroke="purple" stroke-width="5" stroke-linejoin="bevel" fill="none" />
</svg>
- 半透明的矩形
<svg width="200" height="200">
<rect x="50" y="50" width="100" height="100" stroke="black" stroke-width="5" stroke-opacity="0.5" fill="red" />
</svg>
参考资料
出站链接
通过合理利用 stroke
属性,SVG 可以创建多种不同样式的图形,增强视觉效果。无论是简单的线条,还是复杂的路径,都可以通过调整 stroke
相关属性来实现丰富的设计效果。
发表回复