评论

Canvas绘制圆角矩形

Canvas绘制圆角矩形

Chrome 99 之前常规操作:

	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();

其中xy表示矩形的起点坐标,widthheight分别表示矩形的宽、高,topLefttopRightbottomRightbottomLeft分别表示矩形左上、右上、右下和左下圆角半径大小。
下面来解读一下arcTo()的语法,以ctx.arcTo(x1,y1,x2,y2,radi)为例。

第一部分

(x1,y1)坐标点,可以分成两块来理解,第一块我们可以理解为当前画笔停留的坐标点到(x1,y1)的一条直线,第二块我们可以理解为即将要绘制圆角的部位,也就是所在矩形的四个顶角的位置。

第二部分

(x2,y2)坐标点,也可以分成两块来理解,第一块我们可以理解为(x1,y1)坐标点到(x2,y2)的一条直线,这条直线与第一部分理解的直线形成一个夹角,那么圆角就绘制在这个夹角(内角)之间,并与夹角两边相切,第二块可以理解为画笔画完当前圆角最后所停留的坐标点。

第三部分

radi那就很容易理解了,也就是当前即将绘制的圆角的半径。

然后以此类推,完成圆角矩形的绘制。

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();
}

结尾祝君开发顺利,生活愉快!

最后一次编辑于  05-08  
点赞 1
收藏
评论
登录 后发表内容