svg描边的动画效果,主要由stroke-dasharray和stroke-dashoffset两个属性实现.
svg的路径动画绘制步骤:
(1) 用getTotalLength()方法获取path的路径总长度
let logo = document.querySelectorAll('.text-box')
// getTotalLength()反回用户代理对路径总长度
console.log(path.getTotalLength())
(2)设置stroke每段虚线的间距和偏移量为总长度
(3)使用动画将偏移量设置为初始值0
stroke-dasharray:每段虚线的偏移距离
stroke-dashoffset:偏移量
如果直接是文字构成,不是通过path绘制,可将stroke-dasharray和stroke-dashoffset设置成100%.
<svg id="text-box" width="1000px" height="200px" fill="none">
<text class="svgText" x="100" y="100">WELCOME</text>
</svg>
#text-box {
background-color: #ccc;
}
text {
font-size: 70px;
font-weight: 900;
stroke-width: 2px;
stroke:chocolate;
fill:transparent;
letter-spacing: 6px;
stroke-dasharray: 100%;
stroke-dashoffset: 100%;
animation: svgStroke 3s ease forwards;
}
@keyframes svgStroke {
90% {
stroke-dashoffset: 0;
}
100% {
stroke-dashoffset: 0;
fill:chocolate;
}
}