延續昨天的上篇,今天進入程式碼實作的分享,在下篇開頭也再分享一次用 interpolate
的小嘗試:
const container = document.getElementById('container');
const box = document.getElementById('box');
const rotation = gsap.utils.interpolate(0, 360);
const scale = gsap.utils.interpolate(0.5, 2);
container.addEventListener('mousemove', function(e) {
const containerWidth = container.offsetWidth;
const containerHeight = container.offsetHeight;
const xProgress = e.offsetX / containerWidth;
const yProgress = e.offsetY / containerHeight;
const rotation = rotation(xProgress);
const scale = scale(yProgress);
gsap.to(box, {
rotation: rotation,
scale: scale,
duration: 0.3,
ease: "power2.out"
});
});
const containerWidth = container.offsetWidth;
const containerHeight = container.offsetHeight;
offsetWidth
和 offsetHeight
都是 HTMLElement 中的 Web API,它們會回傳一個以 像素 (px)
為單位的數值,代表指定元素在頁面上佔用的尺寸。
const xProgress = e.offsetX / containerWidth;
const yProgress = e.offsetY / containerHeight;
offsetX
跟 offsetY
是 MouseEvent(滑鼠事件)的 Web API,它們用來取得滑鼠指標相對於當前事件目標元素(在這裡是 container)的左上角邊緣 x 軸與 y 軸位置。
將左上角設定為座標原點 (0,0) 是一種慣例,是由 Web API 所制定的標準。
Reference: MDN - Coordinate systems
因為要將滑鼠的絕對像素距離,轉換成 0 到 1 之間的數值,以便提供 interpolate
參數,讓它能準確地計算出滑鼠當前位置應對應的旋轉角度或縮放比例。
const rotation = rotation(xProgress);
const scale = scale(yProgress);
gsap.to(box, {
rotation: rotation,
scale: scale,
duration: 0.3,
ease: "power2.out"
});
container.addEventListener('mouseleave', function() {
gsap.to(box, {
rotation: 0,
scale: 1,
duration: 0.6,
ease: "back.out(1.7)"
});
});