多張相同圖片以參數方程軌跡圍繞鼠標指針旋轉,形成動態視覺效果。代碼兼容 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);
}
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 避免圖片阻擋頁面點擊。