CSS关键帧动画循环间轻微卡顿问题咨询
解决初始0度摇摆动画的循环卡顿问题
问题描述
需要实现类似船只在波浪上摇摆的元素动画,要求初始状态为0度旋转,但当前实现的动画在从100%循环回0%时存在轻微卡顿,关键帧代码如下:
@keyframes rocking2 { 0% { transform: rotate(0deg); } 25% { transform: rotate(-5deg); animation-timing-function: ease-out; } 75% { transform: rotate(5deg); animation-timing-function: ease-in-out; } 100% { transform: rotate(0deg); animation-timing-function: ease-in; } }
卡顿原因
卡顿的核心是动画循环首尾的速度不连续:
- 100%状态使用
ease-in,动画结束时速度趋近于0 - 循环回到0%时,动画从静止状态突然进入
ease-out的加速过程,产生视觉卡顿 - 对比粉色div的流畅动画,其首尾状态一致(均为
rotate(-5deg)),且全程使用ease-in-out,循环点速度保持连续,因此无卡顿
解决方案:保证首尾速度连续
要实现无缝循环,需让动画在100%结束时的速度与0%开始时的速度一致,以下是两种可行方案:
方案1:调整关键帧缓动逻辑
修改关键帧的缓动函数,让100%到0%的过渡与0%到25%的过渡自然衔接:
@keyframes rocking-fixed { 0% { transform: rotate(0deg); animation-timing-function: ease-out; } 25% { transform: rotate(-5deg); animation-timing-function: ease-in-out; } 75% { transform: rotate(5deg); animation-timing-function: ease-out; } 100% { transform: rotate(0deg); animation-timing-function: ease-in-out; } }
给元素应用动画时保持animation-iteration-count: infinite,此时100%结束时的速度会和0%起始时的速度平滑衔接,消除卡顿。
方案2:利用animation-direction: alternate简化逻辑
将动画设计为单向摇摆,通过交替播放方向实现循环,自动保证首尾衔接:
@keyframes rocking-alternate { 0% { transform: rotate(0deg); animation-timing-function: ease-out; } 50% { transform: rotate(-5deg); animation-timing-function: ease-in-out; } 100% { transform: rotate(5deg); } }
元素的动画配置:
.blue-div { animation: rocking-alternate 2s infinite alternate; }
alternate会让动画在偶数次循环时反向播放,从100%回到0%时会遵循反向缓动逻辑,自然保持速度连续。
内容的提问来源于stack exchange,提问作者DA2.
相关产品推荐
相关产品推荐

