≪ Today I learned. RSS購読
公開日
タグ
JavaScript
著者
ダーシノ(@bc_rikko)

Web Animations APIを使ったアニメーション管理方法

Web Animations APIを使うことで、UI上での複雑なアニメーションを管理しやすくなった。

サンプル

  1. Element#animate()でkeyframeを設定する
  2. animate()を呼び出すとすぐにアニメーションが開始されるのでAnimation#pause()で停止する
  3. スタートボタンを押す
    1. Element#play()でアニメーション実行する
    2. 1000ms止まる
    3. Element.reverse()で逆再生する
<div class="item">one</div>
<div class="item">two</div>
<div class="item">three</div>
<button type="button" id="start">start</button> 
const sleep = ms => {
  return new Promise(resolve => {
    setTimeout(() => resolve(), ms)
  })
}

async function start() {
  const items = document.querySelectorAll('.item');

  items.forEach((item, i) => {
    // 初期位置
    item.style.transform = `translate(0px, ${i * 20}px)`
  })

  const animations = Array.from(items).map((item, i) => {
    // それぞれの要素に keyframe を設定
    const animation = item.animate([
      { transform: `translate(0px, ${i * 20}px)` },
      { transform: `translate(${100 * (i + 1)}px, ${i * 20}px)` },
    ], {
      duration: 1000,
      fill: 'both'
    })

    // animate()呼び出すとアニメーションが開始されるので即停止
    animation.pause()
    return animation
  })

  const player = animations.map(a => {
    a.playbackRate = 1
    // アニメーション実行
    a.play()
    // Promiseを返す
    return a.finished
  })

  await Promise.all(player)

  await sleep(1000)

  const reverse = animations.map(a => {
    // 反転
    a.reverse()
    // Promiseを返す
    return a.finished
  })

  await Promise.all(reverse)
}

document.querySelector('#start').addEventListener('click', () => {
  start()
})

デモ

one
two
three