CanvasRenderingContext2D: roundRect() 方法

Baseline 已廣泛支援

此功能已成熟,並且在許多裝置和瀏覽器版本中都能正常工作。自 ⁨2023 年 4 月⁩ 起,所有瀏覽器均已支援此功能。

Canvas 2D API 的 CanvasRenderingContext2D.roundRect() 方法會將一個圓角矩形新增到當前路徑中。

角的半徑的指定方式與 CSS 的 border-radius 屬性非常相似。

與其他修改當前路徑的方法一樣,此方法不會直接渲染任何內容。要將圓角矩形繪製到畫布上,您可以使用 fill()stroke() 方法。

語法

js
roundRect(x, y, width, height, radii)

引數

x

矩形起始點的 x 軸座標,單位為畫素。

y

矩形起始點的 y 軸座標,單位為畫素。

width

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

height

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

radii

一個數字或列表,用於指定用作矩形角的圓弧的半徑。半徑的數量和順序的用法與 widthheight正數時的 CSS border-radius 屬性相同。

  • all-corners
  • [all-corners]
  • [top-left-and-bottom-right, top-right-and-bottom-left]
  • [top-left, top-right-and-bottom-left, bottom-right]
  • [top-left, top-right, bottom-right, bottom-left]

如果 width負數,則圓角矩形會水平翻轉,因此通常應用於左角的半徑值會應用於右角,反之亦然。同樣,當 height 為負數時,圓角矩形會垂直翻轉。如果任何邊的長度小於頂點組合半徑,則指定的半徑可能會被縮放(減小)。

radii 引數也可以是 DOMPointDOMPointReadOnly 例項,或者包含相同屬性的物件({x: 0, y: 0}),或者此類物件的列表,或者混合了數字和此類物件的列表。

返回值

無(undefined)。

異常

RangeError

如果 radii 是一個包含零個或多個元素(多於四個)的列表,或者其中一個值是負數。

示例

繪製矩形

此示例使用 roundRect() 方法建立了多個圓角矩形路徑。然後使用 stroke() 方法渲染這些路徑。

HTML

html
<canvas id="canvas" width="700" height="300"></canvas>

JavaScript

首先,我們建立一個用於繪製圓角矩形的上下文。

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

下面的程式碼繪製了兩個矩形,它們都從點 (10, 20) 開始,寬度為 150,高度為 100。第一個矩形以紅色繪製,並使用單個數字作為引數指定所有角的半徑為零。第二個矩形以藍色繪製,並指定一個 40px 的半徑,作為列表中的單個元素。

js
// Rounded rectangle with zero radius (specified as a number)
ctx.strokeStyle = "red";
ctx.beginPath();
ctx.roundRect(10, 20, 150, 100, 0);
ctx.stroke();

// Rounded rectangle with 40px radius (single element list)
ctx.strokeStyle = "blue";
ctx.beginPath();
ctx.roundRect(10, 20, 150, 100, [40]);
ctx.stroke();

在上一個矩形下方,我們繪製了一個橙色矩形,它指定了相對角的半徑值。

js
// Rounded rectangle with 2 different radii
ctx.strokeStyle = "orange";
ctx.beginPath();
ctx.roundRect(10, 150, 150, 100, [10, 40]);
ctx.stroke();

最後,我們繪製了兩個具有四個半徑值且起始點相同的圓角矩形。這裡的區別在於第二個矩形是以負寬度繪製的。

js
// Rounded rectangle with four different radii
ctx.strokeStyle = "green";
ctx.beginPath();
ctx.roundRect(400, 20, 200, 100, [0, 30, 50, 60]);
ctx.stroke();

// Same rectangle drawn backwards
ctx.strokeStyle = "magenta";
ctx.beginPath();
ctx.roundRect(400, 150, -200, 100, [0, 30, 50, 60]);
ctx.stroke();

結果

結果如下圖所示。對於右側的兩個矩形,請注意底部矩形是如何以負寬度繪製的,以及這如何水平翻轉矩形。

規範

規範
HTML
# dom-context-2d-roundrect

瀏覽器相容性

另見