先來看一下今天的成果,每點擊畫面一下,小鳥就會隨機產生位移:
<body>
<div class="bird1">
<svg width="150" height="172" viewBox="0 0 334 258" fill="none" xmlns="http://www.w3.org/2000/svg">
// 中間省略
</svg>
</div>
<div class="bird2">
<svg width="120" height="172" viewBox="0 0 262 258" fill="none" xmlns="http://www.w3.org/2000/svg">
// 中間省略
</svg>
</div>
</body>
GSAP 有許多 Utility Methods,random 就是其中一個,簡單來說,這些 Methods 就是讓大家可以更輕鬆做出多變的動畫效果~
本篇只使用了 random
的第一個方法,先來看一下結構:
random(minimum, maximum[, snapIncrement, returnFunction])
x
、y
,還可以控制 rotation
、opacity
、scale
等等。snapIncrement
是一個數值,這裡假設最小值為 2,最大值為 20,如果 snapIncrement
設為 3,GSAP 會從最小值開始,每隔 3 設置一個可選值,也就是:2, 5, 8, 11, 14, 17, 20,如果隨機產生的數字是 13,最後就會自動選出離它最近的值(也就是 14)。returnFunction
這裡要寫的是布林值,false
是預設,表示直接回傳一個隨機的值;如果是寫 true
,GSAP 會返回一個可重複用的函式,這個函式每次被呼叫時,都會根據最初設定的範圍,生成一個新的隨機值。透過 random
,只要使用者點擊畫面空白處,就能讓小鳥的方向與旋轉上產生隨機變化:
const birds = document.querySelectorAll(".bird1, .bird2");
document.addEventListener("click", () => {
gsap.to(birds, {
x: () => gsap.utils.random(-100, 400),
y: () => gsap.utils.random(-200, 200),
rotation: () => gsap.utils.random(-30, 30),
duration: 1,
ease: "power2.out"
});
});
第九天,終於~