萬盛學電腦網

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

Canvas 實戰:太陽系行星公轉動畫模擬

利用 Canvas 繪製太陽系行星公轉是展示變換矩陣、動畫循環、徑向漸變與物件導向設計的絕佳案例。本文提供完整可運行代碼,模擬八大行星按真實公轉周期比例運行。

核心設計思路

  • 行星類:封裝位置、半徑、顏色漸變、公轉周期、繪製邏輯
  • 坐標變換:translate(中心) + rotate(角度) 實現公轉
  • 徑向漸變:createRadialGradient 營造球體立體感
  • 動畫循環:setInterval 定時清屏重繪

完整實現代碼

<canvas id="canvas" width="1000" height="1000" style="background: #000"></canvas>

<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const CX = 500, CY = 500; // 畫布中心

// 繪製軌道
function drawOrbits() {
  ctx.strokeStyle = '#fff';
  ctx.lineWidth = 1;
  for (let i = 0; i < 8; i++) {
    ctx.beginPath();
    ctx.arc(CX, CY, (i + 1) * 50, 0, Math.PI * 2);
    ctx.stroke();
  }
}

// 行星構造函數
function Planet(x, y, radius, cycle, startColor, endColor) {
  this.x = x;
  this.y = y;
  this.radius = radius;
  this.cycle = cycle;      // 公轉周期(幀數比例)
  this.startColor = startColor;
  this.endColor = endColor;
  this.time = 0;           // 當前幀計數
  this.gradient = null;

  this.draw = function() {
    ctx.save();
    ctx.translate(CX, CY);
    // 旋轉角度:time * 360° / cycle → 弧度
    ctx.rotate(this.time * 2 * Math.PI / this.cycle);
    
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
    
    // 徑向漸變:從中心到邊緣
    this.gradient = ctx.createRadialGradient(
      this.x, this.y, 0,
      this.x, this.y, this.radius
    );
    this.gradient.addColorStop(0, this.startColor);
    this.gradient.addColorStop(1, this.endColor);
    
    ctx.fillStyle = this.gradient;
    ctx.fill();
    ctx.restore();
    
    this.time++;
  };
}

// 八大行星數據(周期為相對幀數比例,非真實天文數值)
const planets = [
  new Planet(0, -50,  10,  87.7,   '#A69697', '#5c3e40'), // 水星
  new Planet(0, -100, 10,  224.7,  '#c4bbac', '#1f1315'), // 金星
  new Planet(0, -150, 10,  365.2,  '#78b1e8', '#050c12'), // 地球
  new Planet(0, -200, 10,  687.0,  '#cec9b6', '#76422d'), // 火星
  new Planet(0, -250, 10,  4332.6, '#c0a48e', '#322'),    // 木星
  new Planet(0, -300, 10,  10759,  '#f7f9e3', '#5c4533'), // 土星
  new Planet(0, -350, 10,  30799,  '#a7e1e5', '#19243a'), // 天王星
  new Planet(0, -400, 10,  60152,  '#0661b2', '#1E3b73')  // 海王星
];

// 太陽
const sun = new Planet(0, 0, 20, 0, '#f00', '#f90');
sun.draw = function() {
  ctx.save();
  ctx.translate(CX, CY);
  ctx.beginPath();
  ctx.arc(0, 0, this.radius, 0, Math.PI * 2);
  this.gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, this.radius);
  this.gradient.addColorStop(0, this.startColor);
  this.gradient.addColorStop(1, this.endColor);
  ctx.fillStyle = this.gradient;
  ctx.fill();
  ctx.restore();
};

// 動畫循環
setInterval(() => {
  ctx.clearRect(0, 0, 1000, 1000);
  drawOrbits();
  sun.draw();
  planets.forEach(p => p.draw());
}, 16); // ~60fps
</script>

關鍵技術解析

1. 變換矩陣實現公轉

ctx.translate(CX, CY);           // 原點移至太陽中心
ctx.rotate(angle);               // 旋轉座標系
ctx.arc(planet.x, planet.y, ...); // 在旋轉後的座標系中畫圓

行星初始位置設在 Y 軸負方向(如 0, -150),旋轉後自動形成圓周運動。

2. 徑向漸變營造 3D 球體感

const grad = ctx.createRadialGradient(x, y, 0, x, y, radius);
grad.addColorStop(0, '#light'); // 中心亮色
grad.addColorStop(1, '#dark');  // 邊緣暗色

模擬光源從中心照射效果,比單一填充色更具立體感。

3. 幀率獨立的時間控制

當前代碼使用幀計數 this.time++,受幀率影響。生產級應用建議改用時間差:

let lastTime = 0;
function animate(time) {
  const delta = time - lastTime;
  lastTime = time;
  planets.forEach(p => p.update(delta)); // 基於時間更新角度
  draw();
  requestAnimationFrame(animate);
}

擴展建議

  • 添加行星自轉(自轉角度獨立更新)
  • 土星光環(繪製橢圓環 + 旋轉)
  • 滾輪縮放、拖拽平移視角
  • 點擊行星顯示詳細信息(isPointInPath 檢測)
  • 使用真實天文數據(軌道半長軸、傾角、離心率)
  • WebGL 版本:大規模粒子系統、真實光照、Shader 材質

這個太陽系模擬展示了 Canvas 面向對象動畫的核心模式:數據模型分離、狀態封裝、變換矩陣驅動運動、統一渲染循環。這種架構思維可直接遷移至遊戲引擎、數據可視化、物理模擬等複雜項目。

copyright © 萬盛學電腦網 all rights reserved