requestAnimationFrame

7 阅读1分钟

requestAnimationFrame(简称 RAF)是 JavaScript 中用于优化动画渲染的 API,它让浏览器在下一次重绘前执行指定的回调函数。适用于复杂动画、滚动效果、游戏循环等场景,替代传统的定时器方案。以下是其核心概念、用法和优势:

用法: 1.动画移动

function draw() {
  const canvas = document.getElementById('canvas');
  const ctx = canvas.getContext('2d');
  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  // 绘制动画元素(如移动的圆形)
  const time = Date.now() / 1000;
  const x = Math.sin(time) * 100 + canvas.width / 2;
  const y = Math.cos(time) * 100 + canvas.height / 2;
  
  ctx.beginPath();
  ctx.arc(x, y, 20, 0, Math.PI * 2);
  ctx.fill();
  
  // 继续下一帧
  requestAnimationFrame(draw);
}
requestAnimationFrame(draw);
//取消动画执行cancelAnimationFrame(draw)

2.元素不可见时暂停

const observer = new IntersectionObserver(
  (entries) => {
    if (entries[0].isIntersecting) {
      animationId = requestAnimationFrame(animate); // 元素可见时启动
    } else {
      cancelAnimationFrame(animationId); // 元素不可见时暂停
    }
  },
  { threshold: 0.1 }
);

observer.observe(document.getElementById('target'));

与 setTimeout/setInterval 的对比

特性requestAnimationFramesetTimeout/setInterval
执行时机浏览器下一次重绘前固定时间间隔(如 16ms)
帧率同步自动匹配屏幕刷新率(如 60fps)可能导致丢帧或卡顿(如设置为 10ms)
性能优化页面不可见时自动暂停继续执行,浪费资源
回调参数提供时间戳(用于计算动画进度)无内置时间参数
应用场景复杂动画、游戏循环、滚动效果简单定时任务(如倒计时)