Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
在〈使用 GSAP 的 ScrollTrigger 製作捲動動畫〉中,我們介紹了 ScrollTrigger 的基礎用法,搭配 gsap.to( onUpdate: callback ); 來做出計數器的捲動特效。
這次,為了要讓〈GSAP 3 使用基礎〉中的示範可以隨捲動而顯示,而一個頁面中不一定只會有一個 h2 標題,因此除了使用 ScrollTrigger 外,還需要可以一次選擇多個元素。
一開始的失敗作品如下:
See the Pen background-crop-scrolltrigger by Eric Chuang (@eric-chuang) on CodePen.
在這個失敗案例中,可以發現在整個頁面執行下來,只有一次觸發的 start 和 end。重新再看了一次官方文件後,看到範例中的這段註解:
scrollTrigger: ".box", // start the animation when ".box" enters the viewport (once)
原來是因為 trigger: '.title-bg' 的方式真的只會觸發「一次」,因此必須透過迴圈的方式來選取物件。因為當下並沒有想到要如何多次觸發,因此把這個失敗的 Codepen 拿到 GSAP 的討論區詢問。稍早前得到一位熱心網友 akapowl 的回覆,將我的問題分解為幾個步驟:
gsap.utils.toArray( '.title-bg' ).forEach() 的方式,直接選取多個元素。gsap.set() 設定預設值。將原本的寫法重新整理後,可以改為以下的作法:
<h2 class="title-bg" data-background="{{背景路徑}}">
標題
</h2>
<h2 class="title-bg" data-background="{{背景路徑 2}}">
標題 2
</h2>/*
* Credit by akapowl.
*/
gsap.utils.toArray( '.title-bg' ).forEach( ( title ) => {
// 透過迴圈的方式選擇多個 title-bg 元素
const splitText = new SplitText( title, { type: 'chars' } );
// 每次都要重新跑過文字分割
const chars = splitText.chars;
// 分割後儲存為 chars 這個物件
gsap.set( chars, { clipPath: 'polygon(0 0, 0 0, 0 100%, 0 100%)' } );
// 用 clip-path 設定文字裁切
gsap.set( title, {
backgroundImage: 'linear-gradient( #fff 100%, transparent 100%), url('
+ title.dataset.background + ')'
})
// 用另一個 .set() 方法,設定當前 title 的背景圖,
// 使用我們在 HTML 的 data-background 這個屬性。
const tl = gsap.timeline({
// 建立時間軸
scrollTrigger: {
trigger: title,
// 以當前選取的物件作為觸發基準
start: 'top center',
toggleActions: "play none none reverse",
markers: true,
}
});
/*
* 這裡才開始真的製作補間動畫。
*/
tl
.to(title, {
duration: 1,
backgroundImage: 'linear-gradient( #fff -100%,transparent 10%),url('
+ title.dataset.background + ')'
})
.to(
chars,
{
duration: 0.5,
clipPath: 'polygon(0 0, 100% 0, 100% 100%, 0 100%)'
})
;
});修改後的執行結果如下:
See the Pen background-crop-scrolltrigger by Eric Chuang (@eric-chuang) on CodePen.
這邊一併附上 akapowl 提供的範本。我做的修正主要是改成利用 data-background 來動態載入背景圖片,因為這種作法在後續搭配 WordPress 程式時比較方便。
See the Pen background-crop-scrolltrigger by Paul Slawik (@akapowl) on CodePen.
GSAP 真的是個坑,就像是 WordPress 一樣。
結論來說,如果你同一個頁面上,會有多個相似的區段,那麼你要先考慮的是透過 forEach 的迴圈方式,來達到選取多個元素的效果。
儘管因為授權方式的關係,並沒有任何一款上架的外掛,能夠搭配 GSAP 函式庫,但其他專精於 WordPress 解決方案的網站公司,如板塊設計或是敲敲設計,在一些進階客製化的專案中,也都會使用 GSAP 來作為解決方案。