如何基于Canvas quadraticCurveTo实现可自定义宽高的圆角矩形绘制
可自定义宽高的Canvas圆角矩形实现
原参考代码的核心局限
给定的参考代码所有路径坐标均为硬编码常量,无法灵活调整矩形的宽度、高度尺寸。原代码实际绘制的是起点坐标(10,10)、整体宽80px、整体高80px、圆角半径10px的固定尺寸圆角正方形,要实现自定义调整能力,核心是将所有硬编码的坐标点替换为可动态传入的参数,完全保留原代码用quadraticCurveTo绘制圆角的逻辑。
实现逻辑拆解
- 提取独立可配置参数:矩形起始横坐标
x、起始纵坐标y、矩形宽度width、矩形高度height、圆角半径radius - 增加参数兜底校验:当传入的圆角半径大于矩形宽度/高度的1/2时,自动取两者的较小值作为实际圆角半径,避免二次贝塞尔路径交叉、绘制异常
- 逐行映射原硬编码的路径逻辑,保证调整尺寸时圆角的视觉曲率和原参考代码完全一致,不会出现变形
可复用实现代码
/** * 基于quadraticCurveTo绘制圆角矩形 * @param {CanvasRenderingContext2D} ctx 画布上下文 * @param {number} x 矩形左上角起始横坐标 * @param {number} y 矩形左上角起始纵坐标 * @param {number} width 矩形整体宽度 * @param {number} height 矩形整体高度 * @param {number} radius 圆角半径 */ function drawRoundRect(ctx, x, y, width, height, radius) { // 圆角半径合法性兜底 const realRadius = Math.min(radius, width / 2, height / 2) ctx.beginPath() // 路径起点:左上角圆角的右端点 ctx.moveTo(x + realRadius, y) // 上侧水平直边 ctx.lineTo(x + width - realRadius, y) // 右上角圆角 ctx.quadraticCurveTo(x + width, y, x + width, y + realRadius) // 右侧垂直直边 ctx.lineTo(x + width, y + height - realRadius) // 右下角圆角 ctx.quadraticCurveTo(x + width, y + height, x + width - realRadius, y + height) // 下侧水平直边 ctx.lineTo(x + realRadius, y + height) // 左下角圆角 ctx.quadraticCurveTo(x, y + height, x, y + height - realRadius) // 左侧垂直直边 ctx.lineTo(x, y + realRadius) // 左上角圆角,闭合路径 ctx.quadraticCurveTo(x, y, x + realRadius, y) // 可根据需求替换为fill()实现填充效果 ctx.stroke() }
使用示例
初始化画布上下文后,直接调用函数传入需要的尺寸参数即可:
const canvas = document.getElementById('newCanvas') const ctx = canvas.getContext('2d') // 绘制一个宽250px、高120px、圆角20px、起点坐标(20,20)的圆角矩形 drawRoundRect(ctx, 20, 20, 250, 120, 20)
注意:调整宽高时不需要逐行修改路径坐标,只要修改传入的width、height、radius参数即可完成自定义尺寸的绘制。
内容的提问来源于stack exchange,提问作者DoctorPok
相关产品推荐
相关产品推荐

