requestAnimationFrame()は、ブラウザのアニメーションを最適化するためのJavaScriptのメソッドです。このメソッドを使用することで、スムーズなアニメーションを実現できます。

requestAnimationFrame()の基本

requestAnimationFrame()は、次のフレームの描画前に実行したい関数を登録するメソッドです。基本的な構文は以下の通りです:

const animate = () => {
  // アニメーションの処理
  requestAnimationFrame(animate);
};

// アニメーションの開始
requestAnimationFrame(animate);

メリット

1. パフォーマンスの最適化

- ブラウザの描画タイミングに合わせて実行されるため、効率的

- 非表示タブでは自動的に停止し、リソースを節約

2. 滑らかなアニメーション

- モニターのリフレッシュレートに同期

- 一般的な60FPSに最適化

実践的な使用例

要素の移動アニメーション

const element = document.querySelector('.target');
let position = 0;

const moveElement = () => {
  position += 2;
  element.style.transform = `translateX(${position}px)`;
  
  if (position < 300) {
    requestAnimationFrame(moveElement);
  }
};

requestAnimationFrame(moveElement);

アニメーションの制御

let animationId;
let isRunning = false;

const startAnimation = () => {
  if (!isRunning) {
    isRunning = true;
    animate();
  }
};

const stopAnimation = () => {
  isRunning = false;
  cancelAnimationFrame(animationId);
};

const animate = () => {
  // アニメーションの処理
  if (isRunning) {
    animationId = requestAnimationFrame(animate);
  }
};

タイムスタンプの活用

requestAnimationFrame()は、タイムスタンプを引数として受け取ることができます:

let startTime;

const animate = (timestamp) => {
  if (!startTime) startTime = timestamp;
  const progress = timestamp - startTime;

  // 経過時間に基づいたアニメーション
  element.style.transform = `translateX(${progress / 10}px)`;

  if (progress < 3000) { // 3秒間実行
    requestAnimationFrame(animate);
  }
};

requestAnimationFrame(animate);

注意点

  • メモリリークを防ぐため、不要になったアニメーションは必ずcancelAnimationFrame()で停止する
  • 複雑な計算は避け、シンプルな処理にとどめる
  • パフォーマンスを考慮し、CSSアニメーションで実現できる場合はそちらを優先する

まとめ

requestAnimationFrame()は、モダンなWebアプリケーションでスムーズなアニメーションを実現するための重要なツールです。適切に使用することで、ユーザー体験を大きく向上させることができます。パフォーマンスを意識しながら、目的に応じた実装を選択することが重要です。