7
2

More than 5 years have passed since last update.

Web Animations API を使ってJavaScriptでAnimationを実装する

Posted at

JavaScriptでアニメーションを実装しようと調べたところ、Web Animation API というものがあるようです。
MDNを見る限りこのAPIはまだまだ新しいようで、Qiitaにも記事が少なかったのでチートシート的にまとめてみます。

Web Animation API とは

choromeやsafariなどの一部プラウザで対応してたり対応してなかったりするようです。

polyfillのスクリプトを読み込むと問題なく使えるようです。どうやらWeb Animation自体は数年前から存在しているようです。

<script src="https://cdn.jsdelivr.net/web-animations/latest/web-animations.min.js"></script>
npm install web-animations-js

基本のアニメーション

const element = document.body;
element.animate({ backgroundColor: ['red', 'blue'] }, 3000);

Element.animate

animationを実行しanimation object を返します。

element.animate(keyframes, option)となっており

第一引数のkeyframesはいくつかフォーマットが用意されています。

const keyframes = [
  { // from
    opacity: 0,
    color: "#fff"
  }, 
  { // to
    opacity: 1,
    color: "#000"
  }
]
const keyframes = {
  opacity: [ 0, 1 ],          // [ from, to ]
  color:   [ "#fff", "#000" ] // [ from, to ]
}

フォーマットについて

第二引数のoptionにはmsの数値かoptionオブジェクトを渡します。

element.animate(keyframes, option)

アニメーションのOption

第二引数に渡すOptionについてです。

const option = {
  duration: 1000,
  easing: 'ease-in',
  iterations: 'Infinity',
  fill: 'backwards',
};

easing

アニメーションカーブを指定できます。デフォルトではlinerになります。
Ease-in ease-in-outなどの他にもsteps(1, end) cubic-bezier(0, 0, 0.58, 1)なども指定できます。

Iterations

アニメーションの回数を指定できます。デフォルトは1です。
無限に繰り返すにはInfinityを指定します。

delay

名前の通り指定秒アニメーションを遅らせることができます。

fill

アニメーション終了後にアニメーション終了時の状態を維持するにはforwardsを、
アニメーション開始前の状態に戻る場合はbackwordsを指定します。


大抵の場合は上記を指定できれば十分だと思いますが、その他にもいくつかオプションがあるようです。

Animation Object

Animation コンストラクタを使ってAnimationオブジェクトを生成します。
element.animateメソッドではanimationが即座に実行されてしまいますが、Animationインターフェースを使う場合は明示的にplay()メソッドを呼ぶ必要があります。

  const element = document.getElementById('body');
  const effect = new KeyframeEffect(
    element,
    { backgroundColor: ['blue', 'orange']},
    1000
  );

 const animation = new Animation(effect, document.timeline)

 animation.play()

Animation

第二引数はデフォルトでdocument.timelineのようです。

KeyframeEffect

メソッド

Animationオブジェクトは以下の制御メソッドが使えます。

  • play() 再生・再開する
  • pause() 一時停止する
  • reverse() 逆再生する
  • cancel() 中断する
  • finish()

アニメーションの状態

Animation.playStateプロパティーを参照するとアニメーションの状態が分かります。

value 説明
idle アニメーション前
running アニメーション中
paused 中断
finished アニメーション完了

イベントハンドラ

アニメーション終了時のコールバックを指定できます。

animation.onfinish = () => console.log('finished');

キャンセル時のイベントも指定できます。

animation.oncancel = () => console.log('canceled');

参考


簡単なAnimationはCSSの方が簡単で良さそうですが、プログラムから制御したい場面ってやっぱりありますよね。ルーレットアプリを作るときとか。今後も色々変更がありそうです。

7
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2