CSSとJavaScriptによるスプライトシートアニメーション

CSSのsteps()タイミング関数とJavaScriptのフレームサイクリングを使用してスプライトシートをアニメーション化します。キャラクターアニメーション、ローディングスピナー、UIトランジションを構築します。

Techniques

詳細な説明

スプライトシートアニメーション

スプライトシートアニメーションは、スプライトシートに配置されたフレームを高速で切り替えて動きの錯覚を作る技術です。これはフリップブックのデジタル版です。

CSSアニメーションとsteps()

CSSはsteps()タイミング関数を使用してスプライトシートをアニメーション化できます:

.walking-character {
  width: 64px;
  height: 64px;
  background: url('walk-sprite.png') no-repeat;
  animation: walk 0.8s steps(8) infinite;
}

@keyframes walk {
  from { background-position: 0px 0px; }
  to { background-position: -512px 0px; }
}

steps(8)関数はブラウザにアニメーションを8つの離散的なステップに分割するよう指示し(スプライトシートの8フレームに一致)、スムーズに補間するのではなく位置間をジャンプします。

主要パラメーター

  • steps(n) — アニメーションのフレーム数
  • animation-duration — 合計サイクル時間(0.8s = フレームあたり10 FPS)
  • background-position — 移動する総距離(フレーム x フレーム幅)
  • infinite — アニメーションを連続ループ

JavaScriptフレームアニメーション

より多くの制御(一時停止、逆再生、速度変更)にはJavaScriptを使用:

class SpriteAnimator {
  constructor(canvas, spriteSheet, frameWidth, frameHeight) {
    this.ctx = canvas.getContext('2d');
    this.sheet = spriteSheet;
    this.fw = frameWidth;
    this.fh = frameHeight;
    this.currentFrame = 0;
    this.frameCount = spriteSheet.width / frameWidth;
    this.fps = 12;
    this.lastTime = 0;
  }

  update(timestamp) {
    const elapsed = timestamp - this.lastTime;
    if (elapsed > 1000 / this.fps) {
      this.currentFrame = (this.currentFrame + 1) % this.frameCount;
      this.lastTime = timestamp;
    }
    this.ctx.clearRect(0, 0, this.fw, this.fh);
    this.ctx.drawImage(
      this.sheet,
      this.currentFrame * this.fw, 0,
      this.fw, this.fh,
      0, 0, this.fw, this.fh
    );
    requestAnimationFrame((t) => this.update(t));
  }
}

CSS専用ローディングスピナーの例

.spinner {
  width: 48px;
  height: 48px;
  background: url('spinner-sprite.png') no-repeat;
  animation: spin 1s steps(12) infinite;
}

@keyframes spin {
  to { background-position: -576px 0; }
}

JavaScriptやGIFファイルなしでスムーズなローディングスピナーを作成し、スプライトシートを通じてサイズ、速度、色を完全に制御できます。

ユースケース

スプライトアニメーションはHTML5ゲームでのキャラクター移動、Webアプリケーションでのカスタムローディングスピナーやマイクロインタラクション、マーケティングサイトでのアニメーションイラスト、GIFファイルに頼らずにアニメーション効果を実現するメールHTMLで使用されます。

試してみる — Sprite Sheet Generator

Drop images here or click to upload

PNG, JPG, SVG, GIF, WebP supported

フルツールを開く