Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
之前曾經提到,為了幫公司網站的動畫加入轉場的交錯效果,因此使用了 stagger 的方法。但是今天在看 GSAP 的相關資料時,發現如果能夠活用位置參數的話,便能夠更有彈性的操作自己的時間軸。
內容目錄
在〈GSAP 3 的使用基礎〉中,曾經提到 GSAP 3 時間軸的基本語法:
// 實體化時間軸
const tl = gsap.timeline();
// 基礎語法
時間軸.方法( '選擇器', {屬性值} );
// 在 to 方法中加入 position 參數
時間軸.to( '選擇器', {屬性值}, 位置 );預設的情況下,會按照 .to 方法的順序,依序執行時間軸的動畫:
See the Pen GSAP Position Parameter Test by Eric Chuang (@eric-chuang) on CodePen.
但是我們在屬性值之後,可以再加入 position 的參數,進一步控制時間軸。接下來,來稍微筆記一下 position 參數使用的值:
透過 "+=秒數" 這個參數,我們可以遞延時間軸執行的時間。透過 "-=秒數",則是可以提前執行的秒數。
See the Pen GSAP Position Parameter += -= by Eric Chuang (@eric-chuang) on CodePen.
如果每個時間軸都要用秒數來計算,一旦當動畫變得更複雜時,便會難以管理,這是因為 "+=" 和 "-=" 的參考對象都是「前一個時間軸物件」。但如果我想要跟前一個時間軸物件同時觸發的時候,該怎麼辦呢?
換句話說,我們來看看下面的兩種情況:
/** 情況一: Circle 與 Triangle 會同時 */
tl.to( square, {duration: 1, x: 400} )
.to( circle, {duration: 1, x: 400}, "+=1" )
.to( triangle, {duration: 1, x: 400}, "-=1" );
/** 情況二: Square, Circle 與 Triangle 會同時 */
tl.to( square, {duration: 1, x: 400} )
.to( circle, {duration: 1, x: 400}, "-=1" )
.to( triangle, {duration: 1, x: 400}, "-=1" );此時,如果使用 "<",便可以很直覺的讓想要同時觸發的動畫同時進行。
/** 情況一: Circle 與 Triangle 會同時 */
tl.to( square, {duration: 1, x: 400} )
.to( circle, {duration: 1, x: 400}, "+=1" )
.to( triangle, {duration: 1, x: 400}, "<" );
/** 情況二: Square, Circle 與 Triangle 會同時 */
tl.to( square, {duration: 1, x: 400} )
.to( circle, {duration: 1, x: 400}, "<" )
.to( triangle, {duration: 1, x: 400}, "<" );
/** 情況三: Square 與 Circle 同時,而 Triangle 會過一秒後執行 */
tl.to( square, {duration: 1, x: 400} )
.to( circle, {duration: 1, x: 400}, "<" )
.to( triangle, {duration: 1, x: 400}, "<+1" );除了利用 "" 來判斷相對時間外,也可以透過數字直接指定動畫要發生的確切秒數。
/** 指定絕對位置 */
tl.to( square, {duration: 1, x: 400} )
.to( circle, {duration: 1, x: 400}, 3 )
.to( triangle, {duration: 1, x: 400}, 5 );
/** 相當於以下的相對位置 */
tl.to( square, {duration: 1, x: 400} )
.to( circle, {duration: 1, x: 400}, "<+1" )
.to( triangle, {duration: 1, x: 400}, "<+1" );我們可以透過 add() 這個方法,建立關鍵影格。主要的語法如下:
時間軸.to( 選擇器, {屬性值} )
.add( "關鍵影格名稱", 時間(絕對/相對) )
.to( 選擇器2, {屬性值}, "關鍵影格名稱" )
.to( 選擇器3, {屬性值}, "關鍵影格名稱+=/-=相對時間" );舉例來說,以下的寫法,會將 circle 與 triangle 組成 group1,並同時執行。
tl.to( square, {duration: 1, x: 400} )
.add( "group1", "+=1" )
.to( circle, {duration: 1, x: 400}, "group1" )
.to( triangle, {duration: 1, x: 400}, "group1" );需記得的是,如果使用標籤來標記關鍵影格時,相對時間會以關鍵影格的時間來計算。
See the Pen GSAP Position Parameter Tag by Eric Chuang (@eric-chuang) on CodePen.