SVG Stroke 属性学习笔记

SVG 是一种可缩放矢量图形语言,具有简洁、高保真度和易于操作的特点。其中 stroke 属性用于定义矢量图形路径的边框样式。

基本语法

stroke 属性可用于 <line>, <rect>, <circle>, <ellipse>, <polygon>, <polyline><path> 元素中,其基本语法如下:

htmlCopy Code
<element stroke="color|url|none" stroke-width="number" stroke-opacity="number" stroke-linecap="butt|round|square" stroke-linejoin="miter|round|bevel" stroke-dasharray="none|array" stroke-dashoffset="number" />

其中:

  • stroke:定义路径边框颜色,默认为黑色。
  • stroke-width:定义路径边框宽度,默认为1。
  • stroke-opacity:定义路径边框透明度,默认为1,取值范围为[0,1]。
  • stroke-linecap:定义路径边框端点样式,可选值有 butt(默认)、roundsquare
  • stroke-linejoin:定义路径拐角处样式,可选值有 miter(默认)、roundbevel
  • stroke-dasharray:定义路径虚线样式,可设置多个参数,其中第一个参数表示实线长度,第二个参数表示虚线长度,以此类推。
  • stroke-dashoffset:定义路径虚线的偏移量。

实例

以下是一些常见的 stroke 属性用法示例:

1. 定义边框颜色和宽度

htmlCopy Code
<rect x="50" y="50" width="100" height="60" stroke="red" stroke-width="2"/>

该示例将一个矩形的边框颜色设置为红色,宽度为2个像素。

2. 定义边框样式

htmlCopy Code
<path d="M50,80 L150,80" stroke="blue" stroke-width="5" stroke-linecap="round"/>

该示例是一条从 (50, 80) 到 (150, 80) 的直线,其边框样式被设置为圆形末端。

3. 定义虚线样式

htmlCopy Code
<polygon points="50,50 100,20 150,50 100,80" stroke="green" stroke-width="4" stroke-dasharray="5,2"/>

该示例绘制了一个四边形,边框颜色为绿色,宽度为4个像素,且边框为虚线样式,其中实线长度为5个像素,虚线长度为2个像素。

4. 定义透明度

htmlCopy Code
<ellipse cx="100" cy="70" rx="60" ry="30" stroke="purple" stroke-width="3" stroke-opacity="0.5"/>

该示例绘制了一个椭圆,其边框颜色为紫色,宽度为3个像素,透明度为0.5。

小结

stroke 属性是 SVG 矢量图形中非常重要的边框样式属性,其用法丰富多样,开发者可以根据具体需求进行设置。