CanvasRenderingContext2D: stroke() 方法

Baseline 已廣泛支援

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

Canvas 2D API 的 CanvasRenderingContext2D.stroke() 方法使用當前的描邊樣式來描畫(描邊)當前路徑或給定路徑。

描邊是沿著路徑的中心線對齊的;換句話說,一半的描邊會繪製在內部,一半繪製在外部。

描邊是使用 非零規則(non-zero winding rule) 進行繪製的,這意味著路徑的交叉點仍會被填充。

語法

js
stroke()
stroke(path)

引數

路徑

一個要描畫的 Path2D 路徑。

返回值

無(undefined)。

示例

一個簡單的描邊矩形

此示例使用 rect() 方法建立一個矩形,然後使用 stroke() 將其繪製到畫布上。

HTML

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

JavaScript

js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
ctx.rect(10, 10, 150, 100);
ctx.stroke();

結果

重複描畫路徑

通常,您希望為要描畫的每個新物件呼叫 beginPath()。如果您不這樣做,則之前的子路徑將保留在當前路徑中,並且每次呼叫 stroke() 方法時都會被描畫。但在某些情況下,這可能是期望的效果。

HTML

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

JavaScript

此程式碼將第一個路徑描畫三次,第二個路徑描畫兩次,第三個路徑描畫一次。

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

// First sub-path
ctx.lineWidth = 26;
ctx.strokeStyle = "orange";
ctx.moveTo(20, 20);
ctx.lineTo(160, 20);
ctx.stroke();

// Second sub-path
ctx.lineWidth = 14;
ctx.strokeStyle = "green";
ctx.moveTo(20, 80);
ctx.lineTo(220, 80);
ctx.stroke();

// Third sub-path
ctx.lineWidth = 4;
ctx.strokeStyle = "pink";
ctx.moveTo(20, 140);
ctx.lineTo(280, 140);
ctx.stroke();

結果

描邊和填充

如果您想同時描畫和填充一個路徑,執行這些操作的順序將決定結果。在此示例中,左側的正方形是以描邊在填充之上的方式繪製的。右側的正方形是以填充在描邊之上的方式繪製的。

HTML

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

JavaScript

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

ctx.lineWidth = 16;
ctx.strokeStyle = "red";

// Stroke on top of fill
ctx.beginPath();
ctx.rect(25, 25, 100, 100);
ctx.fill();
ctx.stroke();

// Fill on top of stroke
ctx.beginPath();
ctx.rect(175, 25, 100, 100);
ctx.stroke();
ctx.fill();

結果

規範

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

瀏覽器相容性

另見