js 实现帧动画
实现帧动画的方法
使用 requestAnimationFrame
requestAnimationFrame 是浏览器提供的 API,用于在下一次重绘之前调用指定的回调函数更新动画,性能优于 setTimeout 或 setInterval。
let start;
let progress = 0;
const duration = 1000; // 动画持续时间(毫秒)
const element = document.getElementById('target');
function step(timestamp) {
if (!start) start = timestamp;
progress = timestamp - start;
const translateX = Math.min(progress / duration * 100, 100);
element.style.transform = `translateX(${translateX}px)`;
if (progress < duration) {
requestAnimationFrame(step);
}
}
requestAnimationFrame(step);
使用 CSS animation
通过 JavaScript 动态添加 CSS 动画类,利用 CSS 的 @keyframes 实现帧动画。
@keyframes moveRight {
from { transform: translateX(0); }
to { transform: translateX(100px); }
}
.animate {
animation: moveRight 1s forwards;
}
const element = document.getElementById('target');
element.classList.add('animate');
使用 canvas 逐帧绘制
通过 canvas 绘制每一帧图像,适合复杂的帧动画或游戏场景。
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let frameCount = 0;
const totalFrames = 60;
function drawFrame() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'blue';
ctx.fillRect(frameCount, 50, 50, 50);
frameCount = (frameCount + 1) % totalFrames;
requestAnimationFrame(drawFrame);
}
drawFrame();
使用第三方库
对于复杂的帧动画需求,可以使用成熟的第三方库如 GSAP、Anime.js 等。
// 使用 GSAP 示例
gsap.to("#target", { x: 100, duration: 1 });
精灵图动画
通过改变 background-position 实现精灵图动画。

const element = document.getElementById('sprite');
let frame = 0;
const frameWidth = 50;
const totalFrames = 10;
function animateSprite() {
frame = (frame + 1) % totalFrames;
element.style.backgroundPosition = `-${frame * frameWidth}px 0`;
requestAnimationFrame(animateSprite);
}
animateSprite();
性能优化建议
- 尽量使用 CSS 动画或 transform 属性,利用硬件加速。
- 避免在动画过程中触发重排(如读取 offsetWidth)。
- 使用 will-change 属性提前告知浏览器元素将变化。
- 对于复杂动画,考虑使用 WebGL 或 OffscreenCanvas。






