CanvasRenderingContext2D: strokeRect() 方法

Baseline 已廣泛支援

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

Canvas 2D API 的 CanvasRenderingContext2D.strokeRect() 方法會根據當前的 strokeStyle 和其他上下文設定,繪製一個帶描邊的(輪廓)矩形。

此方法直接繪製到畫布上,而不會修改當前路徑,因此任何後續的 fill()stroke() 呼叫都不會對其產生影響。

語法

js
strokeRect(x, y, width, height)

strokeRect() 方法繪製一個帶描邊的矩形,其起始點位於 (x, y),尺寸由 widthheight 指定。

引數

x

矩形起始點的 x 軸座標。

y

矩形起始點的 y 軸座標。

width

矩形的寬度。正值表示向右,負值表示向左。

height

矩形的高度。正值表示向下,負值表示向上。

返回值

無(undefined)。

示例

一個簡單的描邊矩形

此示例使用 strokeRect() 方法繪製一個帶有綠色輪廓的矩形。

HTML

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

JavaScript

矩形的左上角位於 (20, 10)。其寬度為 160,高度為 100。

js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
ctx.strokeStyle = "green";
ctx.strokeRect(20, 10, 160, 100);

結果

應用各種上下文設定

此示例繪製一個帶有陰影和厚實斜邊輪廓的矩形。

HTML

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

JavaScript

js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
ctx.shadowColor = "#dd5533";
ctx.shadowBlur = 20;
ctx.lineJoin = "bevel";
ctx.lineWidth = 15;
ctx.strokeStyle = "#3388ff";
ctx.strokeRect(30, 30, 160, 90);

結果

規範

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

瀏覽器相容性

另見