Web Animations API 流畅动画与性能优化实战概述WAAPI 提供声明式与可编程的动画接口,支持在合成线程执行,提高流畅度并简化控制逻辑。核心概念与参数`element.animate(keyframes, options)` 创建动画;返回 `Animation` 实例。控制:`play()`、`pause()`、`reverse()`、`finish()` 与 `updatePlaybackRate()`。复用:将关键帧与选项复用到多个元素,统一节奏。特性检测:`'animate' in Element.prototype`。实践示例<button id="btn">播放</button> <div class="box"></div> <style> .box { width: 80px; height: 80px; background: #4c8bf5; border-radius: 12px; } </style> <script> const box = document.querySelector('.box'); const kf = [ { transform: 'translateX(0)', opacity: 1 }, { transform: 'translateX(240px)', opacity: 0.8 } ]; const opts = { duration: 800, easing: 'ease-out', fill: 'forwards' }; let anim; if ('animate' in Element.prototype) { anim = box.animate(kf, opts); anim.pause(); } document.getElementById('btn').addEventListener('click', () => anim && anim.play()); </script> 验证方法性能:在 DevTools Performance 中观察主线程任务与合成线程动画分布。控制:验证 `pause/play/reverse` 的状态一致与可中断性。降级:在不支持环境回退为 CSS 动画或过渡。注意事项优先对 `transform`/`opacity` 动画,避免触发布局与绘制。控制动画数量与叠加,防止合成开销过高。在 `prefers-reduced-motion` 下提供禁用或轻量替代。

发表评论 取消回复