iT邦幫忙

2025 iThome 鐵人賽

DAY 12
0
自我挑戰組

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

Day12 - 做一些跟著滑鼠舞動的星星

  • 分享至 

  • xImage
  •  

今天想要分享的是會跟著滑鼠一起移動的小星星,先來看一下效果:
小星星

先來看一下 HTML

<body>
  <div class="star"></div>
  <div class="star"></div>
  <div class="star"></div>
  <div class="star"></div>
  <div class="star"></div>
</body>

CSS

body {
      margin: 0;
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
      background: #007074;
      overflow: hidden;
}
    
.star {
  position: absolute;
  width: 15px;
  height: 15px;
  background: #FEA405;
  clip-path: polygon(
        //省略
  );
}

這裡唯一要注意的點是要有 position: absolute ,因為 .star 預設會是 position: static,它們會變成 Flexbox 的子項目,視覺上就會變成並排的一列星星,而不是重疊的樣子。


實作部分

const stars = document.querySelectorAll(".star");
    
document.addEventListener("mousemove", (e) => {
    const centerX = window.innerWidth / 2;
    const centerY = window.innerHeight / 2;
      
    const offsetX = e.clientX - centerX;
    const offsetY = e.clientY - centerY;
      
    gsap.to(stars, {
      x: offsetX,
      y: offsetY,
      scale: 1 + e.clientY / window.innerHeight, 
      rotation: e.clientX / 5, 
      duration: 0.5,
      ease: "power2.out",
      stagger: 0.05 
    });
});

(待補上)
/images/emoticon/emoticon46.gif


上一篇
Day11 - 用 interpolate 伸縮自如(下)
系列文
從 0 開始學 GSAP 馬拉松之旅12
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言