Canvas 路徑繪製核心三步驟:beginPath() 開始新路徑 → moveTo()/lineTo() 定義路徑 → stroke() 或 fill() 渲染。本文示範基本折線繪製。
| 方法 | 說明 |
|---|---|
beginPath() | 清空當前路徑,開始新路徑 |
moveTo(x, y) | 移動筆觸到 (x,y),不畫線 |
lineTo(x, y) | 從當前點畫直線到 (x,y) |
stroke() | 沿路徑描邊 |
closePath() | 連回起點閉合路徑 |
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #ccc"></canvas>
<script>
const ctx = document.getElementById('myCanvas').getContext('2d');
ctx.beginPath();
ctx.moveTo(10, 10); // 起點
ctx.lineTo(150, 50); // 第2點
ctx.lineTo(10, 50); // 第3點
// ctx.closePath(); // 可選:自動連回起點形成三角形
ctx.strokeStyle = '#333';
ctx.lineWidth = 2;
ctx.stroke();
</script>
</body>
</html>
ctx.lineWidth = 3;
ctx.strokeStyle = 'rgba(255,0,0,0.8)';
ctx.lineCap = 'round'; // 'butt'|'round'|'square' 線端樣式
ctx.lineJoin = 'round'; // 'miter'|'round'|'bevel' 交點樣式
ctx.setLineDash([5, 10]); // 虛線模式 [畫, 空]
ctx.lineDashOffset = 0; // 虛線偏移(可動畫)
function drawLine(ctx, x1, y1, x2, y2, style = {}) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
Object.assign(ctx, style);
ctx.stroke();
}
// 使用
drawLine(ctx, 10, 10, 100, 10, { strokeStyle: 'red', lineWidth: 2 });
drawLine(ctx, 10, 20, 100, 20, { strokeStyle: 'blue', lineWidth: 1, lineDash: [4, 4] });
掌握 `moveTo`/`lineTo`/`stroke` 三部曲即可繪製任意折線。記得每條獨立線段呼叫 `beginPath()` 避免路徑汙染,善用 `lineCap`/`lineJoin`/`setLineDash` 豐富線條表現。