0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptで複数の画像を表示するアニメーションを考える【中級編⑤】

Posted at

はじめに

今回は、JavaScriptを用いて画像をゆっくり表示するアニメーションを制作していきます。

複数の画像を表示する

See the Pen 複数の画像を表示する by Uka Suzuki (@uukasuzuki_) on CodePen.

JavaScriptのコード解説

const items = document.querySelectorAll(".img-item");

for (let i = 0; i < items.length; i++) {
  const keyframes = {
    opacity: [0, 1],
  };
  const options = {
    duration: 600,
    delay: i * 300,
    fill: "forwards",
  };
  items[i].animate(keyframes, options);
}
  • このコードは、複数の.img-itemクラスを持つ要素に対して、順番にフェードインするアニメーションを実装しています。for (let i = 0; i < items.length; i++)では、forループを使って、取得したすべての.img-itemに対して処理を繰り返しています。iはループの回数(インデックス)を示します。

  • const keyframesは、keyframes は、アニメーションのプロパティの変化を定義しています。今回は opacity(不透明度)を0から1に変化させるアニメーションを設定しています。[0, 1]は、最初に完全に透明(0)で、最終的に完全に表示される(1)状態になることを示しています。

  • const optionsのdelay: i * 300では、各要素のアニメーションはインデックス i に300ミリ秒を掛けた値だけ遅延します。つまり、1番目の要素はすぐに実行され、2番目の要素は300ミリ秒後、3番目は600ミリ秒後にアニメーションが開始されます。加えて、fill: "forwards"はアニメーションが終了した後、最後の状態(opacity: 1)を保持します。

  • items[i].animate(keyframes, options)は、animateメソッドは、指定されたkeyframesとoptions を使用して、.img-itemに対してアニメーションを実行します。ここでは、各.img-item要素に対して順番にフェードインのアニメーションが適用されます。

回転する画像

See the Pen Untitled by Uka Suzuki (@uukasuzuki_) on CodePen.

下から浮き上がる画像

See the Pen 下から浮き上がる画像 by Uka Suzuki (@uukasuzuki_) on CodePen.

ふわふわと落ちてくる画像

See the Pen ふわふわと落ちてくる画像 by Uka Suzuki (@uukasuzuki_) on CodePen.

ぼかしてはっきり表示させる画像

See the Pen ぼかしてはっきり表示させる画像 by Uka Suzuki (@uukasuzuki_) on CodePen.

まとめ

今回は、複数の画像に対して表示するアニメーションの仕組みについてまとめました。これらをもとに、Webサイト制作を行う際は、スクロールと組み合わせて考えたいと思います。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?