JavaScriptのアニメーションを扱う際、`requestAnimationFrame()`を使用してスムーズなアニメーションを実装することがありますが、アニメーションを途中で停止したい場合があります。そんなときに使用するのが`cancelAnimationFrame()`メソッドです。
この記事では、`cancelAnimationFrame()`の基本的な使い方から実践的な例まで、詳しく解説します。
cancelAnimationFrame()とは
`cancelAnimationFrame()`は、`requestAnimationFrame()`によって予約されたアニメーションフレームをキャンセルするためのメソッドです。
基本的な使い方
// アニメーションIDを格納する変数
let animationId;
function animate() {
// アニメーションの処理
animationId = requestAnimationFrame(animate);
}
// アニメーションを開始
animate();
// アニメーションを停止
cancelAnimationFrame(animationId);実践的な例:ボックスのアニメーション
以下は、クリックでアニメーションを開始/停止できる簡単な例です。
const box = document.querySelector('.box');
let animationId;
let position = 0;
function moveBox() {
position += 2;
box.style.transform = `translateX(${position}px)`;
if (position < 300) {
animationId = requestAnimationFrame(moveBox);
}
}
// 開始ボタンのクリックイベント
startButton.addEventListener('click', () => {
moveBox();
});
// 停止ボタンのクリックイベント
stopButton.addEventListener('click', () => {
cancelAnimationFrame(animationId);
});注意点
1. `cancelAnimationFrame()`は、アニメーションIDを引数として受け取ります
2. アニメーションIDは`requestAnimationFrame()`の戻り値として取得できます
3. キャンセル後に再開する場合は、新たに`requestAnimationFrame()`を呼び出す必要があります
実装のベストプラクティス
1. アニメーションIDはグローバルまたはクラス内で管理する
2. アニメーション開始前に前回のアニメーションを必ずキャンセルする
3. コンポーネントのクリーンアップ時にアニメーションをキャンセルする
class Animation {
constructor() {
this.animationId = null;
}
start() {
// 既存のアニメーションをキャンセル
if (this.animationId) {
this.stop();
}
const animate = () => {
// アニメーション処理
this.animationId = requestAnimationFrame(animate);
};
animate();
}
stop() {
if (this.animationId) {
cancelAnimationFrame(this.animationId);
this.animationId = null;
}
}
cleanup() {
this.stop();
}
}まとめ
`cancelAnimationFrame()`は、JavaScriptでアニメーションを制御する上で重要なメソッドです。適切に使用することで、スムーズなアニメーション制御とメモリリークの防止が可能になります。
特に以下の点を覚えておくと良いでしょう:
- アニメーションIDの管理が重要
- 適切なタイミングでのキャンセル処理
- クリーンアップ処理の実装
これらの知識を活かして、より洗練されたアニメーション制御を実装してください。