Parallax

Javascript

GSAPの読み込み

<script src="https://cdn.jsdelivr.net/npm/gsap@3.12.7/dist/gsap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/gsap@3.12.7/dist/ScrollTrigger.min.js"></script>

スクロールトリガーを使うので、2行目も必要です

Javascript

スクロールトリガーを使うときは必ずregisterPluginします

gsap.registerPlugin(ScrollTrigger);
gsap.utils.toArray(".parallax").forEach( item => {
    const y = item.getAttribute("data-y") || -100; ※1
    gsap.to(item, {  ※4
        y: y.
        scrollTrigger: {
            trigger: item,
            start: "top bottom", ※3
            end: "bottom top",
            scrub: 1,  ※2
        }
    });
});

※1 … data-y属性の値が大きくなるほど上に向かって急激に上がります

※2 … 遅延時間っぽい

※3 … itemのtopが画面のbottomに来たときにスタートさせる

※4 … toだとy方向に0から-100px移動となるので、画像のサイズによっては下側が見切れてしまいます

HTML

<div class="normal"></div>
<section>
    <div class="parallax"><img src=""></div>
</section>
<div class="normal"></div>

CSS

.normal {
    width: 100%;
    height: 300px;
    background: #f2f2f2;
    z-index: 99;  // パララックスさせる画像よりも上に置く
}
.parallax {
    width: 100%;
    height: auto;
}

今回は、sectionの背景画像をパララックスさせます

参考

背景画像が上から下に移動し、人や物は下から上に移動している【https://www.sliderrevolution.com/templates/artistic-parallax-slider/?utm_medium=youtube&utm_source=template

https://gsap.com/community/forums/topic/30623-parallax-image-backgrounds-with-scrolltrigger-smooth-scrollbar-js-and-scrollerproxy/

https://codepen.io/hakoirioyaji/pen/vYWyRyo

素材を作成する必要があります【https://www.youtube.com/watch?v=2yBk1giIfqE&t=49s

BACK