iT邦幫忙

2025 iThome 鐵人賽

DAY 16
0
Modern Web

在Vibe Coding 時代一起來做沒有AI感的漂亮網站吧!系列 第 16

GSAP Timeline(tl)——做出沉浸式網頁效果,進入你的世界

  • 分享至 

  • xImage
  •  

嗨咿,我是 illumi!是不是常常滑到「教你做出說故事的網站」,想學用程式寫,結果點開發現是figma prototype?

一起用GSAP 的 Timeline (tl) ,讓整個網站一打開,就像電影一樣帶觀眾一步步「沈浸式進入場景」吧。

就像在 After Effects (AE) 裡面拉時間軸、安排每個圖層的關鍵影格,GSAP 的 Timeline 也能把多個動畫串起來,甚至再搭配 ScrollTrigger,讓使用者滾動的同時推進動畫,營造「進場感」。
Yes


為什麼要用 Timeline呢~

在 AE 中,如果你只調整單一物件的透明度,那直接拉關鍵影格就行;但如果你要讓

  1. LOGO 先淡入 → 再往上移動 → 背景接著展開 → 最後字卡依序出現
  2. 大小 / 透明度 / 旋轉…… 任一屬性有多個關鍵影格

那不用時間軸就會很亂。

在網頁動畫中,如果用單一 gsap.to,你就得一個接一個排 setTimeout,超難維護。

Timeline可以幫你把所有動畫整合在一個comp中一起播放!


ScrollTrigger 的屬性解釋

tl.to(".section", {
  scrollTrigger: {
    trigger: ".section",
    start: "top top",
    end: "+=1000%",
    scrub: 1,
    pin: true,
    pinSpacing: true,
  },
  opacity: 1,
  duration: 1,
});

屬性 解釋 AE 剪輯概念類比
start: "top top" 當元素頂部碰到視窗頂部時啟動動畫 入點設定 (In Point)
end: "+=1000%" 動畫結束在往後 1000% 的捲動長度 延長片段時間,決定「持續多久」
scrub: 1 滾動條與動畫綁定,數字代表延遲秒數 拖曳時間軸,幀幀對應
pin: true 在動畫期間固定元素不跟隨滾動 固定圖層在畫布上
pinSpacing: true 是否保留固定元素佔據的空間 是否要留白,像是佔位軌道

實作環節!

把工具叫出來

import { useRef, useState, useEffect } from "react";
import { useGSAP } from "@gsap/react";
import gsap from "gsap";
import ScrollTrigger from "gsap/ScrollTrigger";

在 return (<> </>)中間寫內容

  <div
        ref={Ref}
        className="w-full h-screen flex flex-col items-center justify-center relative snap-auto snap-center snap-always"
      >
      
      放入你的內容
  </div>

在export default function 你的元件名字() { }中間寫功能

  const Ref = useRef<HTMLDivElement>(null);
  
  useGSAP(() => {
    if (!Ref.current) return;
    const tl = gsap.timeline();
    tl.to(Ref.current, {
      keyframes: [
        { scale: 1, opacity: 0 },
        { scale: 1, opacity: 1 },
        { scale: 10, opacity: 1 },
        { scale: 10, opacity: 1 },
        { scale: 5, opacity: 1 },
      ],
      duration: 1,
      scrollTrigger: {
        trigger: Ref.current,
        start: "top top",
        end: "+=1000%",
        scrub: 1,
        pin: true,
        pinSpacing: true,
      },
    });
  });

這樣畫面放大漸顯就有入場感了!

小提醒:

整體都會放大,要注意字太大或是圖片解析度的問題喔!


進階:把 Timeline 玩出電影感

範例:

const tl = gsap.timeline({
  scrollTrigger: {
    trigger: ".hero",
    start: "top top",
    end: "+=2000%",
    scrub: 1,
    pin: true,
  },
});

// Logo 淡入
tl.to(".logo", { opacity: 1, y: -50, duration: 1 });

// 背景展開
tl.to(".background", { scale: 1.2, duration: 2 }, "-=0.5");

// 文字依序出現
tl.to(".headline", { opacity: 1, y: 0, duration: 1 });
tl.to(".subtext", { opacity: 1, y: 0, duration: 1 }, "-=0.5");

這裡幾個重點:

  • 相對時間控制 ("-=0.5"):就像 AE 中把兩段剪輯重疊半秒,讓動畫銜接更自然。
  • 滾動推進:用戶滑多少,你的動畫就走多少。

Yes
效果就是這樣啦!我們明天再見~


上一篇
GSAP Tween 一起讓物件有霹哩啪拉爆炸散開效果
下一篇
Hold On! GSAP你先借我滑鼠控制權滑別的東西
系列文
在Vibe Coding 時代一起來做沒有AI感的漂亮網站吧!21
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言