stroke-dasharray 虚线

详细介绍SVG的stroke-dasharray虚线属性,学习如何创建各种虚线、点划线效果。通过实例掌握虚线样式的设置技巧。 stroke-dasharray属性用于创建虚线效果,通过定义实线和间隙的长度来控制线条样式。

基本语法

<element stroke-dasharray="长度序列"/>

长度序列由一组数值组成,用逗号或空格分隔,依次表示实线长度、间隙长度、实线长度、间隙长度...

基本虚线

简单虚线

10 10,5 10,5,2,5
<line x1="30" y1="30" x2="270" y2="30" stroke="#3498db" stroke-width="3" stroke-dasharray="10"/>
<line x1="30" y1="50" x2="270" y2="50" stroke="#e74c3c" stroke-width="3" stroke-dasharray="10,5"/>
<line x1="30" y1="70" x2="270" y2="70" stroke="#2ecc71" stroke-width="3" stroke-dasharray="10,5,2,5"/>

常见虚线样式

虚线 5,5 长虚线 10,5 点线 2,4 点划线 15,5,5,5 双点划线 20,5,5,5,5,5 密集点 1,3
<line x1="30" y1="30" x2="270" y2="30" stroke="#3498db" stroke-width="2" stroke-dasharray="5,5"/>
<line x1="30" y1="60" x2="270" y2="60" stroke="#3498db" stroke-width="2" stroke-dasharray="10,5"/>
<line x1="30" y1="90" x2="270" y2="90" stroke="#3498db" stroke-width="2" stroke-dasharray="2,4"/>
<line x1="30" y1="120" x2="270" y2="120" stroke="#3498db" stroke-width="2" stroke-dasharray="15,5,5,5"/>
<line x1="30" y1="150" x2="270" y2="150" stroke="#3498db" stroke-width="2" stroke-dasharray="20,5,5,5,5,5"/>
<line x1="30" y1="180" x2="270" y2="180" stroke="#3498db" stroke-width="2" stroke-dasharray="1,3"/>

奇偶数参数

当参数个数为奇数时,序列会自动重复一次形成偶数个参数。

10 → 10,10 10,5,2 → 10,5,2,10,5,2 15,5,5 → 15,5,5,15,5,5
<line x1="30" y1="30" x2="270" y2="30" stroke="#3498db" stroke-width="3" stroke-dasharray="10"/>
<line x1="30" y1="60" x2="270" y2="60" stroke="#e74c3c" stroke-width="3" stroke-dasharray="10,5,2"/>
<line x1="30" y1="90" x2="270" y2="90" stroke="#2ecc71" stroke-width="3" stroke-dasharray="15,5,5"/>

应用到形状

虚线效果可以应用到任何有描边的图形上。

矩形 圆形 多边形
<rect x="20" y="20" width="80" height="80" fill="none" stroke="#3498db" stroke-width="3" stroke-dasharray="10,5"/>
<circle cx="180" cy="60" r="40" fill="none" stroke="#e74c3c" stroke-width="3" stroke-dasharray="5,3"/>
<polygon points="270,20 300,80 240,80" fill="none" stroke="#2ecc71" stroke-width="3" stroke-dasharray="8,4,2,4"/>

实际应用

地图路线

起点 终点
<path d="M 30,100 Q 80,30 150,80 T 270,50" fill="none" stroke="#e74c3c" stroke-width="4" stroke-dasharray="10,5"/>
<circle cx="30" cy="100" r="6" fill="#3498db"/>
<circle cx="270" cy="50" r="6" fill="#2ecc71"/>

边框装饰

虚线边框效果
<rect x="30" y="30" width="240" height="90" fill="#f8f9fa" stroke="#3498db" stroke-width="2" stroke-dasharray="15,5,5,5"/>
<text x="150" y="80" text-anchor="middle" font-size="14" fill="#333">虚线边框效果</text>

刻度线

0 50 100
<line x1="30" y1="50" x2="270" y2="50" stroke="#333" stroke-width="2"/>
<line x1="30" y1="45" x2="270" y2="45" stroke="#3498db" stroke-width="1" stroke-dasharray="10,20"/>
<line x1="30" y1="55" x2="270" y2="55" stroke="#e74c3c" stroke-width="1" stroke-dasharray="5,25"/>