svg描边动画使用stroke-dasharray与stroke-dashoffset两个属性:
一、stroke-dasharray
stroke-dasharray属性可将svg图形的路径断为虚线,如下代码是一条直线:
<svg x="0" y="0" width="500px" height="100px" viewBox="0 0 500 100">
<line id="line" x1="0" y1="6" x2="500" y2="6" stroke="#3896fe"></line>
</svg>
如添加stroke-dasharray:10 10属性后,变为下图:
可见直线被分为了间隔为10px的虚线,若实现描边效果只需将stroke-dasharray设置为路径长度即可,使用以下代码可获取路径长度:
document.querySelector('#path').getTotalLength();
二、stroke-dashoffset
stroke-dashoffset可设置路径的偏移量,设置该值后,路径就会偏移设置的值,如上图使用的直线,配合使用stroke-dasharray属性可将直线消失:
#line{
stroke-dasharray: 500 500;
stroke-dashoffset: 500;
}
利用以上两个属性配合CSS3的animation动画即可实现SVG的描边效果,以下是利用SVG描边做的动画效果:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
.checkmark{
width: 52px;
height:52px;
display: block;
stroke:#ffffff;
border-radius: 50%;
box-shadow: inset 0px 0px 0px #7ac142;
animation: fill .5s ease-in-out .4s forwards,scale .3s ease-in-out .9s both;
}
#circle{
stroke-dasharray: 156.07 156.07;
stroke-width: 2;
fill: none;
stroke: #7ac142;
animation: stroke 0.6s cubic-bezier(0.65,0,0.45,1) forwards;
}
#path{
stroke-dasharray: 48;
fill:none;
stroke-dashoffset: 48;
animation: stroke2 0.6s cubic-bezier(0.65,0,0.45,1) .8s forwards;
}
@keyframes stroke {
0%{
stroke-dashoffset: 156.07;
}
100%{
stroke-dashoffset: 0;
}
}
@keyframes stroke2 {
100%{
stroke-dashoffset: 0;
}
}
@keyframes fill {
100%{
box-shadow: inset 0 0 0 30px #7ac142;
}
}
@keyframes scale {
100%{
transform: scale3d(1.1,1.1,1);
}
}
</style>
<body>
<svg viewBox="0 0 52 52" class="checkmark">
<circle id="circle" cx="26" cy="26" r="25" fill="none"></circle>
<path id="path" d="M14.1 27.2 l7.1 7.2 16.7-16.8" fill="none"></path>
</svg>
</body>
</html>