CanvasRenderingContext2D: bezierCurveTo() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

Canvas 2D API 的 CanvasRenderingContext2D.bezierCurveTo() 方法會將一個三次 Bézier 曲線新增到當前子路徑。它需要三個點:前兩個是控制點,第三個是終點。起點是當前路徑中的最後一個點,可以在建立 Bézier 曲線之前使用 moveTo() 進行更改。

語法

js
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)

引數

cp1x

第一個控制點的 x 軸座標。

cp1y

第一個控制點的 y 軸座標。

cp2x

第二個控制點的 x 軸座標。

cp2y

第二個控制點的 y 軸座標。

x

終點的 x 軸座標。

y

終點的 y 軸座標。

返回值

無(undefined)。

示例

bezierCurveTo 的工作原理

本示例展示瞭如何繪製三次 Bézier 曲線。

HTML

html
<canvas id="canvas"></canvas>

JavaScript

js
// Define canvas and context
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

// Define the points as {x, y}
let start = { x: 50, y: 20 };
let cp1 = { x: 230, y: 30 };
let cp2 = { x: 150, y: 80 };
let end = { x: 250, y: 100 };

// Cubic Bézier curve
ctx.beginPath();
ctx.moveTo(start.x, start.y);
ctx.bezierCurveTo(cp1.x, cp1.y, cp2.x, cp2.y, end.x, end.y);
ctx.stroke();

// Start and end points
ctx.fillStyle = "blue";
ctx.beginPath();
ctx.arc(start.x, start.y, 5, 0, 2 * Math.PI); // Start point
ctx.arc(end.x, end.y, 5, 0, 2 * Math.PI); // End point
ctx.fill();

// Control points
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(cp1.x, cp1.y, 5, 0, 2 * Math.PI); // Control point one
ctx.arc(cp2.x, cp2.y, 5, 0, 2 * Math.PI); // Control point two
ctx.fill();

結果

在此示例中,控制點為紅色,起點和終點為藍色。

簡單的 Bézier 曲線

本示例使用 bezierCurveTo() 繪製了一條簡單的 Bézier 曲線。

HTML

html
<canvas id="canvas"></canvas>

JavaScript

曲線從 moveTo() 指定的點 (30, 30) 開始。第一個控制點位於 (120, 160),第二個控制點位於 (180, 10)。曲線結束於 (220, 140)。

js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.moveTo(30, 30);
ctx.bezierCurveTo(120, 160, 180, 10, 220, 140);
ctx.stroke();

結果

規範

規範
HTML
# dom-context-2d-beziercurveto-dev

瀏覽器相容性

另見