JavaScript の animate() で作る「拡大 → 回転 → 色変化」の連鎖アニメーション

JavaScript の animate() メソッドを使えば、CSS を書かずに「拡大 → 回転 → 色変化」といった複数の動きを順番に実行できます。

この記事では、クリックすると丸が
「拡大 → 回転 → 色変化 → 元に戻る」
という一連のアニメーションをする仕組みを解説します。


完成イメージ

クリックすると、丸がふわっと動いて色が変わります。


ファイル構成

js-lesson/
├── index.html
├── style.css
└── script.js

HTML

<section>
  <h1>クリックで連鎖アニメーション</h1>

  <div class="circle"></div>

  <button id="anim-btn">動かす!</button>

  <script src="./script.js"></script>
</section>

CSS

section {
  font-family: "Yu Gothic", sans-serif;
  background: #f7f8fa;
  text-align: center;
  margin-top: 5rem;
}

.circle {
  width: 100100px;
  height: 100px;
  background: #6c5ce7;
  border-radius: 50%;
  margin: 3rem auto;
}

button {
  padding: 0.6rem 1.2rem;
  background: #6c5ce7;
  color: #fff;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: opacity 0.3s ease;
}
button:hover {
  opacity: 0.8;
}

JavaScript

const circle = document.querySelector(".circle");
const button = document.querySelector("#anim-btn");

button.addEventListener("click", async () => {
  // ① 拡大
  await circle.animate(
    [{ transform: "scale(1)" }, { transform: "scale(1.5)" }],
    { duration: 400, easing: "ease-out", fill: "forwards" }
  ).finished;

  // ② 回転
  await circle.animate(
    [{ transform: "rotate(0deg)" }, { transform: "rotate(360deg)" }],
    { duration: 600, easing: "ease-in-out", fill: "forwards" }
  ).finished;

  // ③ 色変化
  await circle.animate(
    [{ background: "#6c5ce7" }, { background: "#ff7675" }],
    { duration: 500, fill: "forwards" }
  ).finished;

  // ④ 初期状態に戻す
  circle.animate(
    [
      { transform: "scale(1.5) rotate(360deg)", background: "#ff7675" },
      { transform: "scale(1) rotate(0deg)", background: "#6c5ce7" }
    ],
    { duration: 400, easing: "ease-out" }
  );
});

解説

animate() は JavaScript だけでアニメーションを作れるメソッドです。

element.animate(
  [{ opacity: 0 }, { opacity: 1 }],
  { duration: 1000 }
);

次に async / await について。

  • async:この関数の中で await を使える宣言
  • await:処理が終わるまで次へ進まない
  • .finished:アニメーション完了を Promise で返す

つまり次の1行はこういう意味です。

await circle.animate(...).finished;

→ 「このアニメが終わるまで待ってから次を実行」

これで、拡大 → 回転 → 色変化 と順番に動かせます。


まとめ

  • animate():JSだけでアニメーションを実行
  • async / await:アニメを順番に進める仕組み
  • .finished:アニメ終了を検知
  • fill: “forwards”:最後の状態を保持

連鎖アニメーションを理解すると Web サイトに動きが出て、表現の幅が大きく広がります。

コメント

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です