萬盛學電腦網

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

Canvas 進階實戰:打造極致逼真的機械錶盤時鐘

在上一篇基礎時鐘基礎上,本文實現一個擁有漸變表盤、立體刻度、數字標識、品牌字樣、三針疊加與中心軸裝飾的高仿真機械錶效果。展示 Canvas 在精細圖形構建、狀態管理、動畫循環上的工程化實踐。

效果特性

  • 徑向漸變表盤(藍→青)
  • 12 個大刻度 + 60 個小刻度
  • 12 個數字標識(Calibri 粗體)
  • 品牌字樣 "canvas" 曲線排版
  • 三針差異化:時針粗/短、分针中、秒針細/紅/長
  • 中心軸裝飾圓 + 秒針尾部配重圓
  • requestAnimationFrame 級流暢動畫(原文用 setTimeout,此處升級)

完整代碼實現

<canvas id="canvas" width="400" height="400" style="border: 1px solid #ccc"></canvas>

<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const CX = 200, CY = 200, R = 150;

function draw() {
  ctx.clearRect(0, 0, 400, 400);
  ctx.save(); // 整體保存
  ctx.translate(CX, CY); // 原點移至中心

  // ===== 1. 表盤漸變 =====
  ctx.save();
  ctx.beginPath();
  for (let i = 0; i < 13; i++) {
    const angle = i * Math.PI / 6;
    ctx.lineTo(Math.sin(angle) * 150, -Math.cos(angle) * 150);
  }
  const grad = ctx.createRadialGradient(0, 0, 0, 0, 0, 130);
  grad.addColorStop(0, '#22f');
  grad.addColorStop(1, '#0ef');
  ctx.fillStyle = grad;
  ctx.fill();
  ctx.closePath();
  ctx.restore();

  // ===== 2. 數字 1-12 =====
  ctx.save();
  ctx.font = 'bold 20px Calibri, sans-serif';
  ctx.fillStyle = '#fff';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  for (let i = 1; i <= 12; i++) {
    const angle = i * Math.PI / 6;
    ctx.fillText(i, Math.sin(angle) * 120, -Math.cos(angle) * 120);
  }
  ctx.restore();

  // ===== 3. 大刻度 =====
  ctx.save();
  ctx.strokeStyle = '#fff';
  ctx.lineWidth = 4;
  ctx.beginPath();
  for (let i = 0; i < 12; i++) {
    const angle = i * Math.PI / 6;
    ctx.moveTo(Math.sin(angle) * 148, -Math.cos(angle) * 148);
    ctx.lineTo(Math.sin(angle) * 135, -Math.cos(angle) * 135);
  }
  ctx.stroke();
  ctx.restore();

  // ===== 4. 小刻度 =====
  ctx.save();
  ctx.strokeStyle = '#fff';
  ctx.lineWidth = 2;
  ctx.beginPath();
  for (let i = 0; i < 60; i++) {
    if (i % 5 === 0) continue;
    const angle = i * Math.PI / 30;
    ctx.moveTo(Math.sin(angle) * 146, -Math.cos(angle) * 146);
    ctx.lineTo(Math.sin(angle) * 140, -Math.cos(angle) * 140);
  }
  ctx.stroke();
  ctx.restore();

  // ===== 5. 品牌字樣 =====
  ctx.save();
  ctx.font = '34px sans-serif';
  ctx.strokeStyle = '#fff';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.strokeText('canvas', 0, 65);
  ctx.restore();

  // ===== 6. 指針繪製 =====
  const now = new Date();
  const h = (now.getHours() % 12) * Math.PI / 6 + now.getMinutes() * Math.PI / 360 + now.getSeconds() * Math.PI / 21600;
  const m = now.getMinutes() * Math.PI / 30 + now.getSeconds() * Math.PI / 1800;
  const s = now.getSeconds() * Math.PI / 30 + now.getMilliseconds() * Math.PI / 30000;

  // 時針
  drawHand(h, 85, 6, '#fff');
  // 分针
  drawHand(m, 105, 4, '#fff');
  // 秒針
  drawHand(s, 120, 2, '#fff');
  
  // 中心軸
  ctx.beginPath();
  ctx.arc(0, 0, 5, 0, Math.PI * 2);
  ctx.fillStyle = 'gray';
  ctx.fill();
  ctx.strokeStyle = '#fff';
  ctx.stroke();

  // 秒針尾部配重
  ctx.save();
  ctx.rotate(s);
  ctx.beginPath();
  ctx.arc(0, -140, 5, 0, Math.PI * 2);
  ctx.fillStyle = 'gray';
  ctx.fill();
  ctx.restore();

  ctx.restore(); // 整體恢復
  requestAnimationFrame(draw);
}

function drawHand(angle, length, width, color) {
  ctx.save();
  ctx.rotate(angle);
  ctx.beginPath();
  ctx.moveTo(0, 10); // 尾部後延
  ctx.lineTo(0, -length);
  ctx.strokeStyle = color;
  ctx.lineWidth = width;
  ctx.lineCap = 'round';
  ctx.stroke();
  ctx.restore();
}

draw();
</script>

工程化關鍵點

1. 模組化繪製函數

將表盤、刻度、數字、指針拆分為獨立邏輯塊,便於維護與復用。實際項目中可封裝為 ClockFace、Hand 類。

2. 精確角度計算

  • 時針:hours*30° + minutes*0.5° + seconds/120°
  • 分针:minutes*6° + seconds*0.1°
  • 秒針:seconds*6° + ms*0.006°

毫秒級精度實現指針平滑連續轉動,而非跳秒。

3. 狀態棧管理

每個繪製單元 save()/restore() 成對使用,確保:

  • 變換矩陣隔離(translate/rotate 不互相影響)
  • 樣式隔離(lineWidth/strokeStyle/font 不污染)
  • 裁剪區隔離

4. 性能優化建議

  • 靜態層(表盤、刻度、數字)預渲染到離屏 Canvas,動畫幀僅重繪指針
  • 使用 requestAnimationFrame 替代 setTimeout,對齊瀏覽器刷新率
  • 避免在循環中創建對象(如漸變對象),預創建復用

離屏緩存優化版核心邏輯

// 初始化時創建靜態層
const staticCanvas = document.createElement('canvas');
staticCanvas.width = 400; staticCanvas.height = 400;
const sctx = staticCanvas.getContext('2d');
// ... 在 sctx 上繪製表盤、刻度、數字、品牌字 ...

function draw() {
  ctx.clearRect(0, 0, 400, 400);
  ctx.drawImage(staticCanvas, 0, 0); // 一次性繪製靜態層
  // 僅繪製動態指針...
  requestAnimationFrame(draw);
}

這個機械錶示例展示了 Canvas 從「能畫出來」到「畫得好、跑得快、好維護」的進階之路。掌握分層渲染、狀態隔離、精確時間驅動、離屏緩存等模式,是構建高性能 Canvas 應用的關鍵。

copyright © 萬盛學電腦網 all rights reserved