如何获取Animation KeyframeEffect对应当前时间的属性值?
获取KeyframeEffect当前属性值的解决方案
你原代码计算结果错误的原因是:KeyframeEffect.getComputedTiming()返回的progress是未经过缓动函数转换的原始时间进度,没有应用你设置的easing规则,所以直接乘属性最终值得到的是线性过渡结果,和你预期的ease曲线不匹配。
针对你的需求(无需修改DOM、纯内存计算数值动画,适配任意时间线、缓动规则),有两种成熟的实现方案:
方案1:临时元素+CSS自定义属性(兼容性最优)
该方案兼容所有支持Web Animations API的浏览器,无需自行处理任何插值、缓动计算逻辑,所有计算由浏览器原生完成,精度和性能都有保障:
// 创建临时元素,无需插入DOM树 const tempEl = document.createElement('div'); const keyframes = new KeyframeEffect(tempEl, [ { // from '--someProp': 0, }, { // to '--someProp': 35, } ], {duration: 2000, easing: 'ease'}) const anim = new Animation( keyframes, document.timeline ) anim.play() requestAnimationFrame(function loop() { // 直接读取经过缓动、时间线计算后的准确属性值 const currentValue = parseFloat(getComputedStyle(tempEl).getPropertyValue('--someProp')) console.log('current value of someProp:', currentValue) if (anim.playState != 'finished') requestAnimationFrame(loop) })
你可以同时动画任意数量的自定义属性,只需要映射为不同的CSS自定义变量即可,拿到的数值可以直接用于WebGL、Canvas绘制等非DOM动画场景。
方案2:getComputedKeyframes原生API(纯内存无DOM)
如果你完全不想涉及DOM操作,可以使用Chrome 84+、Firefox 75+、Safari 15.4+支持的getComputedKeyframes()方法实现纯内存计算:
const keyframes = new KeyframeEffect(null, [ { // from someProp: 0, }, { // to someProp: 35, } ], {duration: 2000, easing: 'ease'}) const anim = new Animation( keyframes, document.timeline ) anim.play() // 工具方法:获取指定属性的当前计算值 function getCurrentAnimatedValue(effect, propName) { const computedKeyframes = effect.getComputedKeyframes(); const currentProgress = effect.getComputedTiming().progress; // 进度为1时直接返回最后一帧的值 if (currentProgress === 1) return computedKeyframes.at(-1)[propName]; // 定位当前进度所属的关键帧区间 let fromKf = computedKeyframes[0], toKf = computedKeyframes.at(-1); for (let i = 0; i < computedKeyframes.length; i++) { if (computedKeyframes[i].offset <= currentProgress) { fromKf = computedKeyframes[i]; } else { toKf = computedKeyframes[i]; break; } } // 计算区间内相对进度并插值 const rangeOffset = toKf.offset - fromKf.offset; const rangeProgress = rangeOffset === 0 ? 0 : (currentProgress - fromKf.offset) / rangeOffset; return fromKf[propName] + (toKf[propName] - fromKf[propName]) * rangeProgress; } requestAnimationFrame(function loop() { console.log('current value of someProp:', getCurrentAnimatedValue(keyframes, 'someProp')) if (anim.playState != 'finished') requestAnimationFrame(loop) })
该方案完全在内存中运行,适配多关键帧、自定义缓动、ScrollTimeline等所有Web Animations支持的场景。
内容的提问来源于stack exchange,提问作者trusktr
相关产品推荐
相关产品推荐

