SVG路径动画(3)
stroke-dasharray
该css属性主要用于在SVG中创建各种虚线
#line1{
stroke: black;
stroke-width: 10px;
stroke-dasharray: 15 7 5 5 5 7;
/*表示:画15px长,空7px,画5px长,空5px,画5px,空7px,后面则循环此过程
所以在画这种特殊样式的虚线时,只需要找出被循环的那部分,然后用stroke-dasharray表示即可*/
}
#line2{
stroke: black;
stroke-width: 10px;
stroke-dasharray: 10;/*表示:画10px,空10px,如此循环*/
}
<svg id="svg">
<line x1="100" y1="100" x2="300" y2="100" id="line1"></line>
<line x1="100" y1="200" x2="300" y2="200" id="line2"></line>
</svg>
stroke-dashoffset
该css属性用于偏移虚线
注意:stroke-dasharray与stroke-dashoffset要配套使用。在无stroke-dasharray的情况下,stroke-dashoffset不起作用
先来看一个简单的例子:
#line1{
stroke: black;
stroke-width: 10;
stroke-dasharray: 10;
stroke-dashoffset: 150;
}
<svg id="svg">
<line x1="0" y1="100" x2="300" y2="100" id="line1"></line>
</svg>
上述代码画图解释为:
上图也表现了stroke-dashoffset的原理
特殊情况
即,当stroke-dasharray的值等于线段长度时,我们用stroke-dashoffset偏移又会怎样
#line1{
stroke: black;
stroke-width: 10;
stroke-dasharray: 300;
stroke-dashoffset: 300;
}
<svg id="svg">
<line x1="0" y1="100" x2="300" y2="100" id="line1"></line>
</svg>
通过上面给出的图片,你应该能容易的想出运行结果
通过上面的讲解,我们来实现一个‘抽风路径’的动画
#svg{
width: 500px;
height: 500px;
border: 1px solid #ccc;
}
#line1{
stroke: black;
stroke-width: 10;
stroke-dasharray: 300;
animation: move 1s linear alternate infinite;
}
@keyframes move{
0%{
stroke-dashoffset: 0;
}
100%{
stroke-dashoffset: 300;
}
}
<svg id="svg">
<line x1="0" y1="100" x2="300" y2="100" id="line1"></line>
</svg>