テキストスライドアニメーション
デモは以下です。
Gsapを使用して繰り返しアニメーションを作成しています。 繰り返しの後3秒待たせて余韻を作ってます。
解説
npm i -D gsap
Gsapをnpm インストールしてください。
CDNでも使えますが、今回はnpmでインストールしています。
今回はGsapのタイムラインを使用しています。 タイムラインへの参照を TL という変数に格納しています。
const TL = gsap.timeline({ repeat: -1, repeatDelay: 3 });
repeat: -1; // タイムラインを無限に繰り返します。
repeatDelay: 3; // 各繰り返し間の遅延を3秒に設定します。
その結果3秒間隔で無限に繰り返すアニメーションが作成されます!(簡単ですね!)
あとはGsapで to() や from()メソッドでアニメーションを作成します! 今回はクリップパスで画像をスライドさせるようなアニメーションを作成しています!
/* javascript */
TL.from(type, {
opacity: 0,
display: "none",
duration: 0.6,
clipPath: "inset(0 100% 0 0)",
}).to(type, {
opacity: 1,
display: "block",
x: 0,
clipPath: "inset(0 0% 0 0)",
duration: 0.6,
});
全体のコード例
<!-- HTML -->
<div
class="js-type not-prose relative mx-auto aspect-square w-full max-w-[500px] border-8 border-white"
>
<figure
class="absolute hidden overflow-hidden opacity-0 [clip-path:inset(0_100%_0_0)]"
>
<img src="/images/1.png" alt="" />
</figure>
<figure
class="absolute hidden overflow-hidden opacity-0 [clip-path:inset(0_100%_0_0)]"
>
<img src="/images/2.png" alt="" />
</figure>
<figure
class="absolute hidden overflow-hidden opacity-0 [clip-path:inset(0_100%_0_0)]"
>
<img src="/images/3.png" alt="" />
</figure>
<figure
class="absolute hidden overflow-hidden opacity-0 [clip-path:inset(0_100%_0_0)]"
>
<img src="/images/4.png" alt="" />
</figure>
</div>
/* javascript */
import gsap from "gsap";
const type = document.querySelector(".js-type");
const types = type.querySelectorAll("figure");
const TL = gsap.timeline({ repeat: -1, repeatDelay: 3 });
if (types) {
types.forEach((type, index) => {
// 最初の要素以外は初めから非表示にする
if (index !== 0) {
gsap.set(type, {
opacity: 0,
display: "none",
clipPath: "inset(0 100% 0 0)",
});
}
// 各要素を順番に表示
TL.from(type, {
opacity: 0,
display: "none",
duration: 0.6,
clipPath: "inset(0 100% 0 0)",
}).to(type, {
opacity: 1,
display: "block",
x: 0,
clipPath: "inset(0 0% 0 0)",
duration: 0.6,
});
// 次の要素がある場合は、現在の要素を非表示にする
if (types[index + 1]) {
TL.to(type, {
opacity: 0,
x: 0,
display: "none",
duration: 0.4,
onComplete: function () {
// アニメーション完了後のコールバック
gsap.set(type, { clipPath: "inset(0 100% 0 0)" });
},
});
}
});
}