把同一張圖鋪成棋盤,然後隨滑鼠移動讓整個場景旋轉、靠近游標的圖會浮起來——這個效果看起來很「WebGL」,其實只用 div 加 img 就能做到。核心是一套手寫的三維旋轉與透視投影,數學並不複雜。
第一步,平移。把物體座標減去「攝影機」座標,變成以視角為原點的相對座標。
第二步,旋轉。分別繞 Y 軸與 X 軸旋轉,用標準的旋轉矩陣:
// 繞 Y 軸 x' = x·cosθy + z·sinθy z' = z·cosθy - x·sinθy // 繞 X 軸 y' = y·cosθx - z·sinθx z' = y·sinθx + z·cosθx
第三步,透視投影。這是最關鍵也最簡單的一步——離得越遠看起來越小:
scale = focalLength / (focalLength + z) screenX = x * scale screenY = y * scale
乘上 scale 之後,再依 scale 調整圖片的寬高與 z-index,立體感就出現了。
如果滑鼠一动場景就硬跟著轉,看起來會很生硬。範例的做法是幫每個角度與攝影機位置包一層緩動器,每幀只往目標移動一小段距離:
function ease(target) {
return {
position: 0,
move(t, speed) { this.position += (t - this.position) * speed; }
};
}
角度用 0.1 的速度追滑鼠,攝影機用 0.025 追目標圖片,兩者不同步,畫面就有一種「重量感」。
const view = {
items: [],
angle: { x: ease(0), y: ease(0) },
camera: { x: ease(0), y: ease(0), focalLength: 350 },
add(img, x, y, z, sw, sh) {
const el = document.createElement('img');
el.src = img.src;
screen.appendChild(el);
el.point3D = { x, y, z: ease(z), sw, sh, w: img.width, h: img.height };
el.onmouseover = () => {
if (this.current === el) return;
this.camera.x.move(el.point3D.x, 1);
this.camera.y.move(el.point3D.y, 1);
el.point3D.z.move(200, 1); // 浮起來
if (this.current) this.current.point3D.z.move(0, 1);
this.current = el;
};
this.items.push(el);
},
animate(el) {
const p = el.point3D;
const x = p.x - this.camera.x.position;
const y = p.y - this.camera.y.position;
p.z.move(p.z.target ?? 0, 0.12);
const { cos: cx, sin: sx } = Math;
const xy = Math.cos(this.angle.x.position) * y - Math.sin(this.angle.x.position) * p.z.position;
const xz = Math.sin(this.angle.x.position) * y + Math.cos(this.angle.x.position) * p.z.position;
const yz = Math.cos(this.angle.y.position) * xz - Math.sin(this.angle.y.position) * x;
const yx = Math.sin(this.angle.y.position) * xz + Math.cos(this.angle.y.position) * x;
const scale = this.camera.focalLength / (this.camera.focalLength + yz);
const w = Math.max(0, Math.round(p.w * scale * p.sw));
const h = Math.max(0, Math.round(p.h * scale * p.sh));
el.style.left = (x * scale + sw / 2 - w / 2) + 'px';
el.style.top = (xy * scale + sh / 2 - h / 2) + 'px';
el.style.width = w + 'px';
el.style.height = h + 'px';
el.style.zIndex = 10000 + Math.round(scale * 1000);
},
run() {
this.angle.x.move(-(mouse.y - sh / 2) * 0.005, 0.1);
this.angle.y.move( (mouse.x - sw / 2) * 0.0025, 0.1);
this.camera.x.move(this.camera.x.target ?? 0, 0.025);
this.camera.y.move(this.camera.y.target ?? 0, 0.025);
this.items.forEach(el => this.animate(el));
requestAnimationFrame(() => this.run());
}
};
用 requestAnimationFrame 取代 setInterval(…, 16)。固定 16 毫秒假設螢幕是 60Hz,在高更新率或低效能裝置上都不準,也容易和瀏覽器的重繪時機錯開。
滑鼠座標要記得掛在 window 上。只監聽容器的 mousemove 會讓游標離開畫面時停止更新,畫面就卡住不動了。
z-index 用 scale 推算很划算。近的大、遠的小,而 zIndex 也應該近的高,兩者用同一個 scale 換算即可,不必另外排序。
img 記得設 position:absolute。否則所有圖會照文件流排成一列,整套座標計算就白做了。
這份實作的精神是:在沒有 3D 加速的時代,只要願意自己算投影,DOM 也能做出真正的立體場景。今天你當然可以改用 CSS transform: translate3d() 交給 GPU 合成,效果更順;但理解這背後的矩陣與除法,對做 Canvas、WebGL 或任何自訂動畫都同樣有用。