三角形是 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>
beginPath():開啟新路徑,清空之前的路徑數據moveTo(x, y):設定起始頂點(提筆)lineTo(x, y):依次連接頂點(落筆畫線)closePath():自動從最後一點連線回起點,閉合路徑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 路徑機制的最佳切入點。理解「移動→連線→閉合→繪製」的四步曲,並熟練運用三角函數計算頂點坐標,即可輕鬆構建任意多邊形、星形、扇形等幾何圖形。