1. Canvas绘制圆角矩形核心原理
在HTML5 Canvas中绘制圆角矩形看似简单,实则包含多个关键参数和绘制逻辑。与普通矩形不同,圆角矩形需要处理四个角的圆弧过渡,这涉及到贝塞尔曲线的精确控制。
核心参数包括:
- x/y:矩形左上角坐标
- width/height:矩形宽高
- cornerRadius:圆角半径(可统一或分别设置四个角)
- fill/stroke:填充与描边样式
绘制原理是通过连接直线段和圆弧段来构造路径:
- 从左上角开始顺时针绘制
- 每个转角处用arcTo()方法创建1/4圆弧
- 圆弧与相邻边通过切线自然连接
重要提示:arcTo()的坐标参数是控制点而非终点,理解这一点才能准确控制曲线弧度
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 基础绘制实现步骤
2.1 基本绘制函数实现
javascript复制function drawRoundedRect(ctx, x, y, width, height, radius) {
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();
}
2.2 参数校验与边界处理
实际开发中需要增加健壮性检查:
``
