详细介绍SVG的stroke-dasharray虚线属性,学习如何创建各种虚线、点划线效果。通过实例掌握虚线样式的设置技巧。 stroke-dasharray属性用于创建虚线效果,通过定义实线和间隙的长度来控制线条样式。
<element stroke-dasharray="长度序列"/>
长度序列由一组数值组成,用逗号或空格分隔,依次表示实线长度、间隙长度、实线长度、间隙长度...
<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"/>
<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"/>
当参数个数为奇数时,序列会自动重复一次形成偶数个参数。
<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>
<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"/>