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?

animate.cssとJavaScriptを組み合わせて、テキストアニメーションを作る【中級編⑦】

Last updated at Posted at 2024-10-16

はじめに

今回は、animate.cssとJavaScriptを組み合わせて、スクロールすることによるテキストアニメーションを考えていきます。

animate.cssとは?

animate.cssは、class名を付けるだけで簡単にアニメーションを実装出来るライブラリを指します。

animate.cssの使い方

animate.cssを読み込む方法は2つあります。今回は、CDNで読み込む方法で進めていきます。

Git Hubからファイルをダウンロードして読み込む
https://github.com/animate-css/animate.css

animate.cssの記述の仕方

See the Pen サンプル by Uka Suzuki (@uukasuzuki_) on CodePen.

①付けたいアニメーションを探す

記述の仕方01.png

②実装する

<div class="animate__animated animate__heartBeat animate__infinite"></div>
  • アニメーションを付けたい要素に、animate__animated(animate.cssの機能を使うために必ず記載する項目) と animate__heartBeat(選んだアニメーションのクラス名)を付けます。今回は、末尾にanimate__infiniteを付けていますが、これはずっと繰り返すという意味です。

スクロールするとテキストが現れる

See the Pen スクロールするとテキストが現れる by Uka Suzuki (@uukasuzuki_) on CodePen.

JavaScriptのコード解説

document.addEventListener("DOMContentLoaded", function () {
  const elements = document.querySelectorAll(".animate-text");

  const observer = new IntersectionObserver(
    (entries, observer) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.classList.add("visible");
          observer.unobserve(entry.target);  // 1回表示されたら監視を解除
        }
      });
    },
    {
      root: null, // ビューポートを基準にする
      rootMargin: "0px 0px -10% 0px", // 表示領域の少し前で発火
      threshold: 0, // 要素が1pxでも見えたら発火
    }
  );

  elements.forEach((element) => {
    observer.observe(element);
  });
});
  • rootMarginでは、"0px 0px -10% 0px"に設定することで、要素がビューポートに対して下から少し手前でアニメーションが発火するようにします。-10%を変更すると、発火するタイミングを早めたり遅くしたり調整可能です。

  • observer.unobserve(entry.target)は、要素が一度表示されたら、再び監視しないようにしています。これにより、すでに表示された要素が再びアニメーションしないようにします。

まとめ

今回は、animate.cssとJavaScriptを組み合わせたテキストアニメーションの仕組みについてまとめました。

これらは、今後ポートフォリオサイト制作でも使用する可能性があるため、より実践的に考えながら制作していきたいと思います。

0
0
2

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?