Webサイトを作成する際、縦スクロールの途中から横スクロールに切り替えるデザインは、
視覚的なインパクトを与える効果的な手法の一つです。
今回は、GSAP(GreenSock Animation Platform)を使用して、
途中から横スクロールに切り替わるサイトを作る方法を解説します。
GSAPとScrollTriggerの導入
まずは、GSAPとScrollTriggerプラグインをCDNまたはnpmを使用して導入します。
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollTrigger.min.js"></script>
HTMLの構造
基本的なHTML構造を作成します。縦スクロールの途中で横スクロールに切り替えるため、横スクロール部分をラップする要素を作成します。
<body>
<section class="vertical">縦スクロールエリア</section>
<section class="horizontal-wrapper">
<div class="horizontal">
<div class="panel">1</div>
<div class="panel">2</div>
<div class="panel">3</div>
<div class="panel">4</div>
</div>
</section>
<section class="vertical">縦スクロールエリア(続き)</section>
</body>
CSSのスタイリング
横スクロール部分を横に並べるため、CSSでスタイルを整えます。
body {
margin: 0;
overflow-x: hidden;
font-family: Arial, sans-serif;
}
.vertical {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
font-size: 2rem;
}
.horizontal-wrapper {
position: relative;
width: 100%;
height: 100vh;
overflow: hidden;
}
.horizontal {
display: flex;
height: 100%;
width: 400vw;
}
.panel {
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
font-size: 3rem;
background-color: lightblue;
border-right: 2px solid white;
}
GSAPで横スクロールを実装
ScrollTriggerを使用して、スクロールに応じて横スクロールアニメーションを実装します。
gsap.registerPlugin(ScrollTrigger);
let horizontalSection = document.querySelector(".horizontal");
let panels = gsap.utils.toArray(".panel");
let scrollWidth = horizontalSection.scrollWidth;
let totalScroll = scrollWidth - window.innerWidth;
gsap.to(horizontalSection, {
x: () => -totalScroll,
ease: "none",
scrollTrigger: {
trigger: ".horizontal-wrapper",
start: "top top",
end: () => "+=" + totalScroll,
scrub: true,
pin: true,
anticipatePin: 1,
}
});
実装のポイント
1).horizontal-wrapper を ScrollTrigger の trigger に設定し、開始地点を制御。
2).horizontal を gsap.to() で横にスライドさせ、 scrub: true でスクロールと同期。
3)pin: true を設定することで、横スクロール中は固定され、スクロールと共に横移動が行われる。
$)end の値を +=” + totalScroll に設定し、全体の横スクロール幅と同期させる。
まとめ
GSAPの ScrollTrigger を使えば、簡単に縦スクロールから横スクロールへ切り替えるサイトを作成できます。視覚的にユニークな演出を加えたい場合に活用してみてください!