Chrome 99之前常規(guī)操作:
ctx.beginPath();
ctx.moveTo(x+topLeft, y);
ctx.arcTo(x+width, y, x+width, y+height, topRight);
ctx.arcTo(x+width, y+height, x, y+height, bottomRight);
ctx.arcTo(x, y+height, x, y, bottomLeft);
ctx.arcTo(x, y, x+width, y, topLeft);
ctx.closePath();
ctx.fill();
其中x、y表示矩形的起點(diǎn)坐標(biāo),width、height分別表示矩形的寬、高,topLeft、topRight、bottomRight、bottomLeft分別表示矩形左上、右上、右下和左下圓角半徑大小。
下面來解讀一下arcTo()的語法,以ctx.arcTo(x1,y1,x2,y2,radi)為例。
第一部分
(x1,y1)坐標(biāo)點(diǎn),可以分成兩塊來理解,第一塊我們可以理解為當(dāng)前畫筆停留的坐標(biāo)點(diǎn)到(x1,y1)的一條直線,第二塊我們可以理解為即將要繪制圓角的部位,也就是所在矩形的四個(gè)頂角的位置。
第二部分
(x2,y2)坐標(biāo)點(diǎn),也可以分成兩塊來理解,第一塊我們可以理解為(x1,y1)坐標(biāo)點(diǎn)到(x2,y2)的一條直線,這條直線與第一部分理解的直線形成一個(gè)夾角,那么圓角就繪制在這個(gè)夾角(內(nèi)角)之間,并與夾角兩邊相切,第二塊可以理解為畫筆畫完當(dāng)前圓角最后所停留的坐標(biāo)點(diǎn)。
第三部分
radi那就很容易理解了,也就是當(dāng)前即將繪制的圓角的半徑。

然后以此類推,完成圓角矩形的繪制。
Chrome 99之后一行代碼:
ctx.roundRect(x, y, width, height, [topLeft, topRight, bottomRight, bottomLeft]);
ctx.fill();
最后可以做下兼容:
if (ctx.roundRect) {
ctx.roundRect(x, y, width, height, [topLeft, topRight, bottomRight, bottomLeft]);
}else {
ctx.beginPath();
ctx.moveTo(x+topLeft, y);
ctx.arcTo(x+width, y, x+width, y+height, topRight);
ctx.arcTo(x+width, y+height, x, y+height, bottomRight);
ctx.arcTo(x, y+height, x, y, bottomLeft);
ctx.arcTo(x, y, x+width, y, topLeft);
ctx.closePath();
}