Canvas 2D 內建二次/三次貝塞爾曲線方法,無需複雜數學即可繪製平滑曲線、閉合路徑。本文從基礎參數到閉合曲線技巧,完整演示核心用法。
| 方法 | 階數 | 控制點數 | 參數數量 | 適用場景 |
|---|---|---|---|---|
quadraticCurveTo(cpx, cpy, x, y) | 二次 | 1 | 4 | 簡單彎曲、單偏移 |
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) | 三次 | 2 | 6 | 複雜 S 型、閉合曲線、精確控制 |
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 1. 開始新路徑
ctx.beginPath();
// 2. 移動到起點
ctx.moveTo(0, 0);
// 3. 繪製曲線
ctx.bezierCurveTo(200, 0, 0, 200, 200, 200); // cp1, cp2, end
// 4. 設定樣式並描邊
ctx.strokeStyle = '#F00';
ctx.stroke();

控制點 (200,0) 和 (0,200) 將直線「拉」成平滑 S 型曲線,終點 (200,200)。
ctx.beginPath();
ctx.strokeStyle = '#00F';
ctx.moveTo(100, 0); // 起點 = 終點
ctx.bezierCurveTo(-100, 200, 300, 200, 100, 0);
ctx.stroke();

關鍵:起點與終點重合,控制點對稱分佈,即可形成閉合回路。多項式插值難以做到此點。
cp2 = 2*end - cp1)可保證 G1 連續(切線連續)ctx.fill() 替代 ctx.stroke(),配合 ctx.closePath() 封閉區域requestAnimationFrame 漸進增加 t 參數繪製路徑片段ctx.isPointInPath(x, y) 或 ctx.isPointInStroke(x, y)