使用 arc 方法
Canvas 的 API 提供了 arc()
方法用来绘制弧线,通过使用该方法我们可以实现圆角效果。
首先,我们需要确定圆角的大小。在下面的例子中,我将圆角大小设置为 20:
const cornerSize = 20;
接下来,我们需要从起点开始绘制我们的圆角矩形。我们可以使用 moveTo()
方法来移动当前路径的起点位置。在下面的代码中,我们将起点移动到 (x+cornerSize, y)
点:
ctx.moveTo(x + cornerSize, y);
然后,我们要绘制右上角的圆角。我们可以使用 arcTo()
方法来完成此操作。下面的语句将从左上角的终点位置开始,并以圆弧方式绘制右上角的圆角(注意,从左上角到右上角的直线段不能小于圆角的直径):
ctx.arcTo(x + width, y, x + width, y + cornerSize, cornerSize);
接下来,我们需要绘制右侧的边,所以我们使用 lineTo()
方法将路径移到右侧的顶部圆角的起点位置:
ctx.lineTo(x + width, y + height - cornerSize);
然后,我们使用 arcTo()
方法以圆弧方式绘制右下角的圆角,路径应该是从右侧顶部开始绘制,并沿着右下角到左侧底部:
ctx.arcTo(x + width, y + height, x + width - cornerSize, y + height, cornerSize);
之后,我们要绘制左侧的边,所以我们使用 lineTo()
方法将路径移到左侧底部圆角的起点位置:
ctx.lineTo(x + cornerSize, y + height);
最后,我们使用 arcTo()
方法以圆弧方式绘制左上角的圆角,路径应该从左侧底部开始绘制,并沿着左上角到右侧顶部,完成路径的闭合:
ctx.arcTo(x, y + height, x, y + height - cornerSize, cornerSize);
最后,我们可以用 closePath()
方法来关闭路径。在下面的代码中,我们设置了一个填充颜色和描边颜色,并使用 fill()
和 stroke()
方法来分别填充和描边矩形:
ctx.closePath();
ctx.fillStyle = 'blue';
ctx.strokeStyle = 'red';
ctx.fill();
ctx.stroke();
整个代码如下所示:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const x = 50;
const y = 50;
const width = 200;
const height = 100;
const cornerSize = 20;
ctx.beginPath();
ctx.moveTo(x + cornerSize, y);
ctx.arcTo(x + width, y, x + width, y + cornerSize, cornerSize);
ctx.lineTo(x + width, y + height - cornerSize);
ctx.arcTo(x + width, y + height, x + width - cornerSize, y + height, cornerSize);
ctx.lineTo(x + cornerSize, y + height);
ctx.arcTo(x, y + height, x, y + height - cornerSize, cornerSize);
ctx.lineTo(x, y + cornerSize);
ctx.arcTo(x, y, x + cornerSize, y, cornerSize);
ctx.closePath();
ctx.fillStyle = 'blue';
ctx.strokeStyle = 'red';
ctx.fill();
ctx.stroke();
总结
使用 arc()
方法可以很容易地在 Canvas 中绘制圆形,而通过 arcTo()
方法可以实现圆角矩形的绘制。使用这种方法可以让
原文链接:https://juejin.cn/post/7231958116722671674 作者:饺子不放糖