前言
在日常开发中,我们经常遇见支付完成的情况,会有一个完成的动画。这次我们用css实现一个这样的动画,话不多说,先看效果:

1. 具体实现
1.1 实现思路
主要使用了SVG 绘制圆形和打钩图形,通过控制stroke-dasharray
和stroke-dashoffset
实现路径绘制效,用CSS动画的delay
属性实现动画序列。
1.2 SVG图形绘制
首先构建SVG基础结构,包含圆形和打钩两个部分:
- 创建一个圆 使用
<circle>
创建了一个圆环,中心在(200,200),半径190px,圆弧的宽度为20,transform="rotate(-90 200 200)"
将圆环旋转-90度,使动画从顶部开始,stroke-linecap="round"
使线条端点圆润 - 创建一个勾 使用
<polyline>
创建了一个勾,由三个点连接而成 ,点坐标points="88,214 173,284 304,138"
,stroke-linejoin="round"
使线条连接处圆滑
xml
<svg width="400" height="400">
<!-- 圆形部分 -->
<circle fill="none" stroke="#68E534" stroke-width="20" cx="200" cy="200" r="190"
class="circle" stroke-linecap="round" transform="rotate(-90 200 200)" />
<!-- 打钩部分 -->
<polyline fill="none" stroke="#68E534" stroke-width="24" points="88,214 173,284 304,138"
stroke-linecap="round" stroke-linejoin="round" class="tick" />
</svg>
具体效果如下:

1.3 添加CSS动画
1.3.1 圆形动画实现
css
.svg .circle {
stroke-dasharray: 1194; /* 圆周长:2πr = 2×3.14×190 ≈ 1194 */
stroke-dashoffset: 1194; /* 初始偏移量等于周长 */
animation: circle 1s ease-in-out;
animation-fill-mode: forwards;
}
@keyframes circle {
from {
stroke-dashoffset: 1194;
}
to {
stroke-dashoffset: 2388; /* 动画结束时偏移量为2倍周长 */
}
}
这部分的功能是:
- 刚开始圆的半径是190px,周长计算为2πr ≈ 1194px,使用
stroke-dasharray: 1194
设置了虚线模式,将它们的 stroke-offset 都设置为图案总长度(即刚好藏起整个图形),这样圆一开始是不可见的(完全偏移掉了)。 - 设置了stroke-offset 的圆环缺口始于它的三点钟方向,并沿着逆时针方向扩展。我们想要路径动画,从圆环的顶部开始。因此我们需要将圆环逆时针旋转 90°。svg中我们可以用transform-origin来完成,让其起始点在顶部
- 再使用动画持续1秒,通过变化stroke-dashoffset的值实现,并且设置
animation-fill-mode
为forwards
,动画会停在最后一帧。
此时效果为:

将stroke-offset设置为偏移250效果为:

将stroke-offset设置为偏移1194效果:

将stroke-offset设置为偏移1200效果:

这样就完成了圆的动画。
1.3.2 打钩动画实现
再来实现下打勾的动画效果,同圆类似,当stroke-dashoffset: 350
时,勾完全消失,变小时慢慢出现。
css
.svg .tick {
stroke-dasharray: 350; /* 打钩路径总长度 */
stroke-dashoffset: 350; /* 初始偏移量 */
animation: tick .8s ease-out;
animation-fill-mode: forwards;
animation-delay: .95s; /* 延迟启动 */
}
@keyframes tick {
from {
stroke-dashoffset: 350;
}
to {
stroke-dashoffset: 0; /* 动画结束时完全显示 */
}
}
1.3.3 文字提示动画
最后再添加个文字动画效果:
css
h2 {
font-size: 36px;
margin-top: 40px;
color: #333;
opacity: 0;
animation: .6s title ease-in-out;
animation-delay: 1.2s; /* 延迟启动 */
animation-fill-mode: forwards;
}
@keyframes title {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
总结
最后总结一下,使用svg绘制图形,使用CSS的stroke-dasharray
和stroke-dashoffset
结合@keyframes
动画,可以实现SVG路径的绘制式进度完成效果。
如有错误,请指正O^O!