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

浏览器兼容性

另见