js实现帧动画效果
使用 requestAnimationFrame 实现帧动画
requestAnimationFrame 是浏览器提供的 API,专门用于优化动画性能。它会自动匹配屏幕刷新率,确保动画流畅且节省资源。
let startTime;
function animate(timestamp) {
if (!startTime) startTime = timestamp;
const progress = timestamp - startTime;
// 更新动画状态
const element = document.getElementById('animated-element');
element.style.transform = `translateX(${Math.min(progress / 10, 200)}px)`;
if (progress < 2000) {
requestAnimationFrame(animate);
}
}
requestAnimationFrame(animate);
使用 CSS @keyframes 结合 JavaScript 控制
CSS 原生动画性能更好,适合简单的关键帧动画。通过 JavaScript 动态添加/移除类来控制动画。
@keyframes slide {
0% { transform: translateX(0); }
100% { transform: translateX(200px); }
}
.animate {
animation: slide 2s forwards;
}
const element = document.getElementById('animated-element');
element.classList.add('animate');
// 动画结束监听
element.addEventListener('animationend', () => {
console.log('动画结束');
});
使用 Canvas 绘制逐帧动画
Canvas 适合需要精细控制的复杂动画,特别是游戏开发场景。
const canvas = document.getElementById('animation-canvas');
const ctx = canvas.getContext('2d');
let frame = 0;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制当前帧内容
ctx.fillStyle = 'red';
ctx.fillRect(frame % canvas.width, 50, 50, 50);
frame++;
requestAnimationFrame(draw);
}
draw();
使用 Web Animations API
现代浏览器支持的 Web Animations API 提供了更强大的动画控制能力。
const element = document.getElementById('animated-element');
const animation = element.animate([
{ transform: 'translateX(0)' },
{ transform: 'translateX(200px)' }
], {
duration: 1000,
iterations: Infinity
});
// 控制动画
animation.pause();
animation.play();
animation.cancel();
使用第三方动画库
对于复杂动画场景,可以考虑使用专业动画库:
- GSAP:功能强大的专业级动画库
- Anime.js:轻量级但功能丰富的动画引擎
- Three.js:3D 动画和 WebGL 渲染
// GSAP 示例
gsap.to("#element", {
x: 200,
duration: 1,
repeat: -1,
yoyo: true
});
性能优化建议
避免强制同步布局(Layout Thrashing),将读取和写入 DOM 的操作分开执行。使用 transform 和 opacity 属性进行动画,这些属性会触发硬件加速。
使用 will-change 属性提前告知浏览器哪些元素会变化:
.animated-element {
will-change: transform;
}
对于移动端,注意减少动画元素数量和复杂度,必要时降低帧率以节省电量。







