zenn_waapi_demo05

by 6242ea4

HTML

<div class="box"></div>
<p>
  <button id="play">play()</button>
  <button id="pause">pause()</button>
  <button id="reverse">reverse()</button>
  <button id="finish">finish()</button>
</p>
<label>currentTime <input id="seek" type="range" min="0" max="1500" value="0"></label>
<label>
  playbackRate
  <select id="rate">
    <option>0.5</option>
    <option selected>1</option>
    <option>2</option>
  </select>
</label>

CSS

.box {
  width: 60px;
  height: 60px;
  margin: 16px;
  background: tomato;
}
label {
  display: block;
  margin: 8px 0;
}

JavaScript

const $ = (selector) => document.querySelector(selector);

const animation = $('.box').animate(
  { transform: ['translateX(0) rotate(0turn)', 'translateX(200px) rotate(1turn)'] },
  { duration: 1500, easing: 'cubic-bezier(.6,-.3,.5,1)', fill: 'both' }
);
animation.pause();

$('#play').addEventListener('click', () => animation.play());
$('#pause').addEventListener('click', () => animation.pause());
$('#reverse').addEventListener('click', () => animation.reverse());
$('#finish').addEventListener('click', () => animation.finish());

// スライダーの値をそのまま再生位置にする
$('#seek').addEventListener('input', (e) => {
  animation.pause();
  animation.currentTime = Number(e.target.value);
});

// 速さを変える(reverse() のあとは向きを保つ)
$('#rate').addEventListener('change', (e) => {
  animation.playbackRate = Math.sign(animation.playbackRate) * Number(e.target.value);
});

// 再生中はスライダーを現在の再生位置に合わせる
(function sync() {
  if (animation.playState === 'running') $('#seek').value = animation.currentTime;
  requestAnimationFrame(sync);
})();