萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

鼠標跟隨旋轉特效:多圖像環繞滑動軌跡實現

效果描述

多張相同圖片以參數方程軌跡圍繞鼠標指針旋轉,形成動態視覺效果。代碼兼容 IE (document.all) 與 Netscape 4 (document.layers) 兩種古老 DOM 模型。

核心數學模型


// 參數方程:x = Xpos + R * cos(θ), y = Ypos + R * sin(θ)
// 其中 R 隨時間變化,θ 隨圖片索引分布
const yBase = window.innerHeight / 4;
const xBase = window.innerWidth / 4;
const step = 0.2;      // 角速度
let currStep = 0;

function Swirl() {
  for (let i = 0; i < amount; i++) {
    const angle = (20 * Math.sin(currStep/20)) + i * 70;
    const radiusMod = Math.sin(10 + currStep/10) + 0.2;
    const phase = (currStep + i * 25) / 10;

    img[i].style.top  = Ypos + Math.cos(angle) * yBase * radiusMod * Math.cos(phase);
    img[i].style.left = Xpos + Math.sin(angle) * xBase * radiusMod * Math.cos(phase);
  }
  currStep += step;
  setTimeout(Swirl, 10);
}

現代化實現 (ES6 + requestAnimationFrame)

class MouseSwirl {
  constructor({ imageUrl, count = 8, container = document.body }) {
    this.images = Array.from({ length: count }, () => {
      const img = new Image();
      img.src = imageUrl;
      img.style.cssText = 'position:fixed;pointer-events:none;z-index:9999;';
      container.appendChild(img);
      return img;
    });
    this.angle = 0;
    this.step = 0.02;
    this.bindMouse();
    this.animate();
  }

  bindMouse() {
    window.addEventListener('mousemove', e => {
      this.mouseX = e.clientX;
      this.mouseY = e.clientY;
    });
  }

  animate() {
    this.angle += this.step;
    const yBase = window.innerHeight / 4;
    const xBase = window.innerWidth / 4;

    this.images.forEach((img, i) => {
      const angle = 20 * Math.sin(this.angle/20) + i * 70;
      const radiusMod = Math.sin(10 + this.angle/10) + 0.2;
      const phase = (this.angle + i * 25) / 10;

      img.style.transform = `translate(${this.mouseX + Math.cos(angle) * xBase * radiusMod * Math.cos(phase)}px, 
                                   ${this.mouseY + Math.sin(angle) * yBase * radiusMod * Math.cos(phase)}px)`;
    });
    requestAnimationFrame(() => this.animate());
  }
}

// 使用
new MouseSwirl({ imageUrl: 'logo.gif', count: 12 });

性能與體驗優化

  • 使用 transform: translate() 代替 top/left,啟用 GPU 加速。
  • pointer-events: none 避免圖片阻擋頁面點擊。
  • 圖片預載入,避免首幀閃爍。
  • 移動端建議關閉或降低幀率,節省電量。
copyright © 萬盛學電腦網 all rights reserved