JS动画卡顿怎么办?requestAnimationFrame 不生效?
我用 requestAnimationFrame 写了个简单的元素移动动画,但页面特别卡,帧率很低,感觉跟没用一样。是不是我写法有问题?
下面是我写的代码,就是让一个 div 每帧往右移 1px:
let x = 0;
const box = document.getElementById('box');
function animate() {
x += 1;
box.style.transform = <code>translateX(${x}px)</code>;
requestAnimationFrame(animate);
}
animate();
控制台也没报错,但动画明显不如 CSS transition 流畅,这是为啥?
如果确实需要精确控制速度,用时间戳计算:
let x = 0;
let lastTime = performance.now();
const speed = 100; // 每秒移动100px
function animate(currentTime) {
const deltaTime = (currentTime - lastTime) / 1000;
x += speed * deltaTime;
box.style.transform =
translateX(${x}px);lastTime = currentTime;
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);