萬盛學電腦網

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

Canvas 繪製三角形:路徑構建、填充描邊與組合圖形技巧

三角形是 Canvas 中通過路徑繪製的最基礎多邊形。本文演示空心與實心三角形繪製,解析 moveTo/lineTo/closePath 的協作機制,並延伸至任意多邊形繪製模式。

基礎代碼示例

<canvas id="canvas" width="500" height="500" style="background: #ffff00"></canvas>

<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// 空心三角形
ctx.beginPath();
ctx.moveTo(250, 50);    // 頂點
ctx.lineTo(200, 200);   // 左下
ctx.lineTo(300, 300);   // 右下(注意:此處形成非等邊三角形)
ctx.closePath();        // 自動連回起點 (250,50)
ctx.strokeStyle = 'red';
ctx.stroke();

// 實心三角形
ctx.beginPath();
ctx.moveTo(350, 50);
ctx.lineTo(300, 200);
ctx.lineTo(400, 300);
ctx.closePath();
ctx.fillStyle = 'blue';
ctx.fill();
</script>

關鍵步驟解析

  1. beginPath():開啟新路徑,清空之前的路徑數據
  2. moveTo(x, y):設定起始頂點(提筆)
  3. lineTo(x, y):依次連接頂點(落筆畫線)
  4. closePath():自動從最後一點連線回起點,閉合路徑
  5. stroke()/fill():執行實際繪製

等邊三角形計算

function drawEquilateralTriangle(ctx, cx, cy, sideLength, orientation = 'up') {
  const h = sideLength * Math.sqrt(3) / 2; // 高度
  const r = h * 2 / 3; // 外接圓半徑(中心到頂點)
  
  ctx.beginPath();
  if (orientation === 'up') {
    ctx.moveTo(cx, cy - r);                    // 頂點
    ctx.lineTo(cx - sideLength/2, cy + h/3);   // 左下
    ctx.lineTo(cx + sideLength/2, cy + h/3);   // 右下
  } else {
    ctx.moveTo(cx, cy + r);                    // 底部頂點
    ctx.lineTo(cx - sideLength/2, cy - h/3);
    ctx.lineTo(cx + sideLength/2, cy - h/3);
  }
  ctx.closePath();
}

通用多邊形繪製函數

function drawPolygon(ctx, cx, cy, radius, sides, startAngle = -Math.PI/2) {
  ctx.beginPath();
  for (let i = 0; i < sides; i++) {
    const angle = startAngle + i * 2 * Math.PI / sides;
    const x = cx + radius * Math.cos(angle);
    const y = cy + radius * Math.sin(angle);
    if (i === 0) ctx.moveTo(x, y);
    else ctx.lineTo(x, y);
  }
  ctx.closePath();
}

// 使用:正五邊形
drawPolygon(ctx, 250, 250, 100, 5);
ctx.strokeStyle = 'purple';
ctx.lineWidth = 3;
ctx.stroke();

組合圖形:星形

function drawStar(ctx, cx, cy, outerR, innerR, spikes = 5) {
  ctx.beginPath();
  for (let i = 0; i < spikes * 2; i++) {
    const angle = -Math.PI/2 + i * Math.PI / spikes;
    const r = i % 2 === 0 ? outerR : innerR;
    const x = cx + r * Math.cos(angle);
    const y = cy + r * Math.sin(angle);
    if (i === 0) ctx.moveTo(x, y);
    else ctx.lineTo(x, y);
  }
  ctx.closePath();
}

填充與描邊組合

ctx.fillStyle = 'gold';
ctx.fill();           // 先填充
ctx.strokeStyle = 'orange';
ctx.lineWidth = 4;
ctx.stroke();         // 再描邊(描邊會覆蓋填充外緣一半)

注意順序:先 fill 再 stroke,否則描邊內側會被填充覆蓋。

常見錯誤

  • 忘記 closePath():fill 仍會自動閉合填充,但 stroke 會缺少最後一邊
  • 坐標計算錯誤導致三角形變形(建議封裝幾何計算函數)
  • 路徑未隔離:多個三角形共用路徑導致樣式混亂

三角形繪製是掌握 Canvas 路徑機制的最佳切入點。理解「移動→連線→閉合→繪製」的四步曲,並熟練運用三角函數計算頂點坐標,即可輕鬆構建任意多邊形、星形、扇形等幾何圖形。

copyright © 萬盛學電腦網 all rights reserved