iT邦幫忙

2025 iThome 鐵人賽

DAY 11
0
自我挑戰組

從 0 開始學 GSAP 馬拉松之旅系列 第 11

Day11 - 用 interpolate 伸縮自如(下)

  • 分享至 

  • xImage
  •  

延續昨天的上篇,今天進入程式碼實作的分享,在下篇開頭也再分享一次用 interpolate 的小嘗試:
縮放剪紙


Step1.先準備好之後要轉換的兩個函式(旋轉與縮放)

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);

Step2. 進行數值轉換核心(mousemove 事件處理)

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"
  });
});

2-1. 取得容器的長與寬(計算基準)

const containerWidth = container.offsetWidth;
const containerHeight = container.offsetHeight;

offsetWidthoffsetHeight 都是 HTMLElement 中的 Web API,它們會回傳一個以 像素 (px) 為單位的數值,代表指定元素在頁面上佔用的尺寸。

2-2. 滑鼠在容器內的相對位置計算

const xProgress = e.offsetX / containerWidth;
const yProgress = e.offsetY / containerHeight;

offsetXoffsetY 是 MouseEvent(滑鼠事件)的 Web API,它們用來取得滑鼠指標相對於當前事件目標元素(在這裡是 container)的左上角邊緣 x 軸與 y 軸位置。


那又為什麼是「左上角邊緣」?

將左上角設定為座標原點 (0,0) 是一種慣例,是由 Web API 所制定的標準。

Reference: MDN - Coordinate systems


為什麼要 offsetX / containerWidth?

因為要將滑鼠的絕對像素距離,轉換成 0 到 1 之間的數值,以便提供 interpolate 參數,讓它能準確地計算出滑鼠當前位置應對應的旋轉角度或縮放比例。


2-3. 進行數值轉換(也就是上一篇的音量調節!)

const rotation = rotation(xProgress);
const scale = scale(yProgress);

2-4. 為元素套用旋轉與縮放動畫

 gsap.to(box, {
    rotation: rotation,
    scale: scale,
    duration: 0.3,
    ease: "power2.out"
  });

Nice to have 的滑鼠離開時重置

container.addEventListener('mouseleave', function() {
    gsap.to(box, {
       rotation: 0,
       scale: 1,
       duration: 0.6,
       ease: "back.out(1.7)"
    });
});

上一篇
Day10 - 用 interpolate 伸縮自如(上)
下一篇
Day12 - 做一些跟著滑鼠舞動的星星
系列文
從 0 開始學 GSAP 馬拉松之旅12
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言