Canvas 繪圖的起點,就是畫一條線。本文通過最簡潔的代碼,演示 Canvas 繪製線段的完整流程,建立正確的路徑繪製心智模型。
<canvas id="canvas" width="400" height="200" style="border: 1px solid #ccc"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 1. 開始新路徑
ctx.beginPath();
// 2. 移動筆尖到起點 (20, 20)
ctx.moveTo(20, 20);
// 3. 畫線到終點 (100, 20)
ctx.lineTo(100, 20);
// 3. 設置樣式
ctx.lineWidth = 10;
ctx.strokeStyle = '#00ff00';
// 4. 執行描邊(實際繪製)
ctx.stroke();
// 5. 關閉路徑(可選,此處無閉合必要)
ctx.closePath();
</script>
beginPath() → moveTo(x,y) → lineTo(x,y) ... → 設置樣式 → stroke()/fill() → closePath()
beginPath()moveTo(x, y)lineTo(x, y)stroke()closePath()beginPath():多次繪製時路徑疊加,導致意外連線stroke() 之後:無效,Canvas 是狀態機moveTo 會畫線:它只是移動筆尖ctx.setLineDash([10, 5]); // 10px 實線,5px 間隙
ctx.lineDashOffset = 0; // 動畫修改此值可實現「螞蟻線」效果
ctx.lineCap = 'round'; // 端點圓滑:butt(默認) / round / square
ctx.lineJoin = 'round'; // 轉角圓滑:miter(默認) / round / bevel
setLineDash 畫虛線框lineCap='round' 畫粗線條對比效果「千里之行,始於足下」。畫線看似簡單,却包含了 Canvas 繪圖的核心範式:路徑構建 → 狀態設置 → 執行繪製。牢固掌握這一流程,後續學習曲線、形狀、動畫才能得心應手。