canvas无原生圆角矩形方法,需用arcto()或arc手动实现;推荐arcto版简洁抗锯齿,增强版支持四角独立半径,可封装为链式调用工具。

Canvas 本身没有直接绘制圆角矩形的原生方法,但可以通过 arcTo() 或路径组合(moveTo、lineTo、arc)手动实现。下面是一个实用、易用的自定义函数,支持描边、填充、内外圆角统一控制。
基础圆角矩形函数(推荐 arcTo 版)
使用 arcTo() 实现更简洁、抗锯齿效果更好,适合大多数场景:
function roundRect(ctx, x, y, width, height, radius) {
if (width ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.arcTo(x + width, y, x + width, y + radius, radius);
ctx.lineTo(x + width, y + height - radius);
ctx.arcTo(x + width, y + height, x + width - radius, y + height, radius);
ctx.lineTo(x + radius, y + height);
ctx.arcTo(x, y + height, x, y + height - radius, radius);
ctx.lineTo(x, y + radius);
ctx.arcTo(x, y, x + radius, y, radius);
ctx.closePath();
}
用法示例:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
<p>// 填充一个蓝色圆角矩形
roundRect(ctx, 50, 50, 200, 100, 15);
ctx.fillStyle = '#4a90e2';
ctx.fill();</p><p>// 再描边(可单独调用 stroke)
ctx.strokeStyle = '#2c3e50';
ctx.lineWidth = 2;
ctx.stroke();</p>
支持独立控制四角半径的增强版
当需要左上、右上、右下、左下分别设置不同圆角时,用 arc() 更灵活:
function roundRectAdvanced(ctx, x, y, width, height, tl = 0, tr = 0, br = 0, bl = 0) {
ctx.beginPath();
ctx.moveTo(x + tl, y);
ctx.lineTo(x + width - tr, y);
ctx.arc(x + width - tr, y + tr, tr, -Math.PI/2, 0, false);
ctx.lineTo(x + width, y + height - br);
ctx.arc(x + width - br, y + height - br, br, 0, Math.PI/2, false);
ctx.lineTo(x + bl, y + height);
ctx.arc(x + bl, y + height - bl, bl, Math.PI/2, Math.PI, false);
ctx.lineTo(x, y + tl);
ctx.arc(x + tl, y + tl, tl, Math.PI, 3*Math.PI/2, false);
ctx.closePath();
}
说明:
- tl/tr/br/bl 分别代表左上、右上、右下、左下圆角半径;未传则默认为 0
- 每个
arc()参数:圆心 x、y,半径,起始弧度,结束弧度,是否逆时针 - 注意坐标偏移逻辑,避免圆角超出矩形边界
封装成可链式调用的绘图工具(可选)
若频繁使用,可扩展 CanvasRenderingContext2D 原型:
CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
this.beginPath();
this.moveTo(x+r, y);
this.lineTo(x+w-r, y);
this.arcTo(x+w, y, x+w, y+r, r);
this.lineTo(x+w, y+h-r);
this.arcTo(x+w, y+h, x+w-r, y+h, r);
this.lineTo(x+r, y+h);
this.arcTo(x, y+h, x, y+h-r, r);
this.lineTo(x, y+r);
this.arcTo(x, y, x+r, y, r);
this.closePath();
return this; // 支持链式
};
<p>// 使用
ctx.roundRect(20, 20, 120, 80, 10)
.fillStyle = '#ff6b6b'
.fill()
.strokeStyle = '#ff4757'
.stroke();</p>
注意事项与常见问题
实际开发中需留意:
- 圆角半径不能超过矩形宽高的一半,否则视觉异常 —— 函数内应做自动截断(如第一版所示)
-
arcTo()在 Safari 旧版本中存在兼容性问题,生产环境建议加简单降级(如全直角回退) - 若开启
ctx.lineJoin = 'round',可能影响非圆角顶点表现,建议保持默认'miter' - 阴影(
shadowBlur)和圆角配合良好,无需额外处理
不复杂但容易忽略细节 —— 掌握其中一种写法,再根据项目需求微调即可高效复用。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










