requestAnimationFrame是什么?【前端】
- 亲爱的读者,希望今天的你好心情~
目录
- requestAnimationFrame是什么?
- 目的?
- 举个栗子:
requestAnimationFrame是什么?
requestAnimationFrame
是一种用于优化动画性能的 JavaScript API。它允许你在浏览器的下一次重绘之前执行动画更新,从而使动画更加流畅和高效。相比于使用 setTimeout
或 setInterval
,requestAnimationFrame
可以让浏览器在绘制动画时更好地协调 CPU 和 GPU 资源,并且能够自动调整动画的执行频率以适应屏幕刷新率。
目的?
- 优化性能:
requestAnimationFrame
使浏览器能够在最佳时机执行动画帧更新,减少不必要的计算和绘制。 - 节省资源:当页面不可见或浏览器窗口被最小化时,requestAnimationFrame 会暂停动画更新,从而节省资源。
- 同步刷新率:它使动画的帧率能够与显示器的刷新率同步,通常是每秒 60 帧(60 FPS),从而使动画更加流畅。
举个栗子:
假设我们要创建一个简单的动画,使一个方块在页面上移动。使用 requestAnimationFrame 可以确保动画流畅运行。(就是一个红色的小方块从左边移动到页面右侧停止。。)
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>requestAnimationFrame Example</title><style>#box {width: 50px;height: 50px;background-color: red;position: absolute;}</style>
</head>
<body><div id="box"></div><script>let box = document.getElementById('box');let position = 0;function animate() {position += 1; // Move the box 1 pixel to the rightbox.style.transform = `translateX(${position}px)`;if (position < window.innerWidth - 50) { // Stop when reaching the edgerequestAnimationFrame(animate); // Request the next frame}}requestAnimationFrame(animate); // Start the animation</script>
</body>
</html>