萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML5 Canvas 3D 入門教學:從點、線到面構建旋轉立方體

核心概念:在 2D 畫布模擬 3D

Canvas 本質是 2D 像素陣列。要呈現 3D,需:

  1. 建立 3D 座標系 (x, y, z)。
  2. **透視投影**:將 3D 座標轉換為 2D 畫布座標 (透過焦距 f 計算縮放比 scale = f / (f + z))。
  3. **深度排序**:依 Z 軸平均值 (面心 Z) 排序,遠面先畫、近面後畫 (Painter's Algorithm)。
  4. **旋轉變換**:應用旋轉矩陣更新所有頂點座標。

階層式物件設計

1. 向量/頂點類別

class Vector {
  constructor(x, y, z) { this.x = x; this.y = y; this.z = z; }

  // 透視投影轉 2D
  get2D(focalLength, centerX, centerY) {
    const scale = focalLength / (focalLength + this.z);
    return {
      x: centerX + this.x * scale,
      y: centerY + this.y * scale
    };
  }

  // 繞 X 軸旋轉
  rotateX(angle) {
    const cos = Math.cos(angle), sin = Math.sin(angle);
    const y = this.y * cos - this.z * sin;
    const z = this.z * cos + this.y * sin;
    this.y = y; this.z = z;
  }

  // 繞 Y 軸旋轉
  rotateY(angle) {
    const cos = Math.cos(angle), sin = Math.sin(angle);
    const x = this.x * cos - this.z * sin;
    const z = this.z * cos + this.x * sin;
    this.x = x; this.z = z;
  }
}

2. 面類別

class Face {
  constructor(v1, v2, v3, v4, color) {
    this.vertices = [v1, v2, v3, v4];
    this.color = color;
    this.zIndex = (v1.z + v2.z + v3.z + v4.z) / 4; // 面心 Z,用於深度排序
  }

  draw(ctx) {
    ctx.save();
    ctx.beginPath();
    const p = this.vertices[0].get2D(focalLength, centerX, centerY);
    ctx.moveTo(p.x, p.y);
    for (let i = 1; i < 4; i++) {
      const p = this.vertices[i].get2D(focalLength, centerX, centerY);
      ctx.lineTo(p.x, p.y);
    }
    ctx.closePath();
    ctx.fillStyle = this.color;
    ctx.fill();
    ctx.restore();
  }
}

3. 立方體類別

class Cube {
  constructor(size) {
    this.size = size;
    this.vectors = [];
    this.faces = [];
    this.initVectors();
  }

  initVectors() {
    const h = this.size / 2;
    // 8 個頂點:前面 4 個 (z=+h),後面 4 個 (z=-h)
    this.vectors = [
      new Vector(-h, -h,  h), new Vector(-h,  h,  h),
      new Vector( h, -h,  h), new Vector( h,  h,  h),
      new Vector( h, -h, -h), new Vector( h,  h, -h),
      new Vector(-h, -h, -h), new Vector(-h,  h, -h)
    ];
  }

  buildFaces() {
    const v = this.vectors;
    this.faces = [
      new Face(v[0], v[1], v[3], v[2], '#6c6'), // 前
      new Face(v[2], v[3], v[5], v[4], '#6cc'), // 右
      new Face(v[4], v[5], v[7], v[6], '#cc6'), // 後
      new Face(v[6], v[7], v[1], v[0], '#c6c'), // 左
      new Face(v[1], v[3], v[5], v[7], '#666'), // 上
      new Face(v[0], v[2], v[4], v[6], '#ccc')  // 下
    ];
  }

  draw(ctx) {
    this.buildFaces(); // 頂點變動後重建面
    this.faces.sort((a, b) => b.zIndex - a.zIndex); // 遠到近排序
    this.faces.forEach(f => f.draw(ctx));
  }

  rotateX(angle) { this.vectors.forEach(v => v.rotateX(angle)); }
  rotateY(angle) { this.vectors.forEach(v => v.rotateY(angle)); }
}

動畫循環與滑鼠互動

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const focalLength = 250;

let angleX = 0, angleY = 0;
const cube = new Cube(100);

// 滑鼠控制旋轉速度
canvas.addEventListener('mousemove', e => {
  const rect = canvas.getBoundingClientRect();
  const mx = e.clientX - rect.left - centerX;
  const my = e.clientY - rect.top - centerY;
  angleY = mx * 0.0001; // 水平位移控制 Y 軸旋轉
  angleX = my * 0.0001; // 垂直位移控制 X 軸旋轉
});

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  cube.rotateY(angleY);
  cube.rotateX(angleX);
  cube.draw(ctx);
  requestAnimationFrame(animate);
}
animate();

擴展方向

  • 光照著色: 計算面法線與光源向量點積,調整 `fillStyle` 亮度 (Lambertian)。
  • 紋理貼圖: `ctx.drawImage` 配合透視修正 (需三角形剖分)。
  • Z-Buffer: 像素級深度測試,解決複雜模型遮擋 (需 WebGL/Three.js)。
  • 物理引擎: 加入重力、碰撞、彈性 (Cannon.js/Ammo.js)。
  • Three.js / Babylon.js: 生產級 3D 引擎,封裝 WebGL,支援模型載入、動畫、後處理、VR/AR。

完整可執行範例 (單檔)

<!DOCTYPE html>
<html><body>
<canvas id="canvas" width="600" height="400" style="border:1px solid #ccc; cursor:crosshair;"></canvas>
<script>
// ... 將上方所有類別與 animate() 代碼貼此處 ...
</script>
</body></html>
copyright © 萬盛學電腦網 all rights reserved