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
分別表示矩形左上线罕、右上止潮、右下和左下圓角半徑大小。
下面來(lái)解讀一下arcTo()
的語(yǔ)法钞楼,以ctx.arcTo(x1,y1,x2,y2,radi)
為例喇闸。
第一部分
(x1,y1)
坐標(biāo)點(diǎn)愉粤,可以分成兩塊來(lái)理解远舅,第一塊我們可以理解為當(dāng)前畫(huà)筆停留的坐標(biāo)點(diǎn)到(x1,y1)
的一條直線(xiàn),第二塊我們可以理解為即將要繪制圓角的部位霜运,也就是所在矩形的四個(gè)頂角的位置宛琅。
第二部分
(x2,y2)
坐標(biāo)點(diǎn)橘沥,也可以分成兩塊來(lái)理解,第一塊我們可以理解為(x1,y1)
坐標(biāo)點(diǎn)到(x2,y2)
的一條直線(xiàn)夯秃,這條直線(xiàn)與第一部分理解的直線(xiàn)形成一個(gè)夾角座咆,那么圓角就繪制在這個(gè)夾角(內(nèi)角)之間,并與夾角兩邊相切仓洼,第二塊可以理解為畫(huà)筆畫(huà)完當(dāng)前圓角最后所停留的坐標(biāo)點(diǎn)介陶。
第三部分
radi
那就很容易理解了,也就是當(dāng)前即將繪制的圓角的半徑色建。
然后以此類(lèi)推哺呜,完成圓角矩形的繪制。
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();
}