缓动函数使用疑难:延迟启动动画时时间变量初始化异常
解决缓动动画延迟启动时时间变量(t)不从0开始的问题
你的问题核心是:当前的时间计算基于代码全局执行的起始点,而非动画实际启动的时间点,导致延迟启动时t直接跳到大值。以下是简洁的修复方案:
核心修改思路
给动画实例新增一个动画启动专属时间戳变量,仅在动画开始执行的第一帧初始化它,后续所有时间计算都基于这个启动时间,而非全局代码启动时间。
修改后的代码
getEaseTimeVar() { const currentTime = performance.now(); // 仅在动画首次启动时初始化启动时间 if (!this.#animationStartTime) { this.#animationStartTime = currentTime; this.#oldTimeStamp = currentTime; this.#secondsPassed = 0; return 0; // 首次返回0,对应缓动函数的起始t值 } // 计算从动画启动到当前的时间差(转换为秒) this.#secondsPassed = (currentTime - this.#animationStartTime) / 1000; this.#oldTimeStamp = currentTime; // 返回动画启动后的累计时间(秒),作为缓动函数的t参数 return this.#secondsPassed; }
注意:需要在类中声明私有变量#animationStartTime,初始值设为null
使用说明
- 延迟启动动画:在延迟触发的逻辑中(比如
setTimeout回调),不要提前调用getEaseTimeVar,直到动画真正开始执行的第一帧再调用,此时#animationStartTime会被初始化为当前时间,后续t会从0开始正常递增。 - 重置动画:如果需要重复播放动画,只需将
this.#animationStartTime = null,下次调用getEaseTimeVar时会重新初始化启动时间。
额外优化提示
缓动函数通常需要的是标准化的t值(范围0-1,代表动画完成进度),你可以在获取到时间差后,结合动画总时长计算:
// 假设动画总时长为2秒 const animationDuration = 2; const normalizedT = Math.min(this.#secondsPassed / animationDuration, 1); // 传入缓动函数使用,比如:easeInOutQuad(normalizedT, startValue, endValue, duration)
内容的提问来源于stack exchange,提问作者aka_lux
相关产品推荐
相关产品推荐

