Appearance
实例:曲线图形-圆角矩形 案例
原生没有绘制圆角矩形的方法,可以用 arcTo
方法也可以用 arc
方法,所以我们封装一个绘制圆角矩形的方法。
方法
js
createRoundedRect(cxt, width, height, r, offsetX, offsetY)
参数说明
- cxt:绘制上下文
- width:圆角矩形的宽度
- height:圆角矩形的高度
- r:圆角半径
- offsetX / offsetY:左上角顶点的横纵坐标
重点几个坐标
- 起始的坐标点:
(offsetX + r, offsetY)
- 四条直线连线的终点位置
(offsetX + width - r, offsetY)
(offsetX + width, offsetY + height - r)
(offsetX + r, offsetY + height)
(offsetX, offsetY + r)
- 四条圆弧的终点位置
(offsetY + width, offsetY + r)
(offsetX + width - r, offsetY + height)
(offsetX, offsetY + height - r)
(offsetX + r, offsetY)
- 弧线的中心点坐标
(offsetX + r, offsetY + r)
(offsetX + width - r, offsetY+ r)
(offsetX + width - r, offsetY + height- r)
(offsetX + r, offsetY + height- r)
封装
js
function createRoundedRect(cxt, width, height, r, offsetX, offsetY) {
cxt.beginPath()
// 上直线
cxt.moveTo(offsetX + r, offsetY)
cxt.lineTo(offsetX + width - r, offsetY)
// 右上弧线
cxt.arcTo(offsetX + width, offsetY, offsetY + width, offsetY + r, r)
// 右直线
cxt.lineTo(offsetX + width, offsetY + height - r)
// 右下弧线
cxt.arcTo(offsetX + width, offsetY + height, offsetX + width - r, offsetY + height, r)
// 下直线
cxt.lineTo(offsetX + r, offsetY + height)
// 左下弧线
cxt.arcTo(offsetX, offsetY + height, offsetX, offsetY + height - r, r)
// 左直线
cxt.lineTo(offsetX, offsetY + r)
// 左上弧线
cxt.arcTo(offsetX, offsetY, offsetX + r, offsetY, r)
cxt.closePath()
}
js
function createRoundedRect(cxt, width, height, r, offsetX, offsetY) {
cxt.beginPath()
// 上直线
cxt.moveTo(offsetX + r, offsetY)
cxt.lineTo(offsetX + width - r, offsetY)
// 右上弧线
cxt.arc(offsetX + width - r, offsetY + r, r, -90 * Math.PI / 180, 0)
// 右直线
cxt.lineTo(offsetX + width, offsetY + height - r)
// 右下弧线
cxt.arc(offsetX + width - r, offsetY + height - r, r, 0, 90 * Math.PI / 180)
// 下直线
cxt.lineTo(offsetX + r, offsetY + height)
// 左下弧线
cxt.arc(offsetX + r, offsetY + height - r, r, 90 * Math.PI / 180, 180 * Math.PI / 180)
// 左直线
cxt.lineTo(offsetX, offsetY + r)
// 左上弧线
cxt.arc(offsetX + r, offsetY + r, r, 180 * Math.PI / 180, 270 * Math.PI / 180)
cxt.closePath()
}
调用
js
const cnv = $$('canvas');
const cxt = cnv.getContext('2d');
// 调用方法绘制圆角矩形路径
createRoundedRect(cxt, 100, 100, 20, 20, 20);
// 设置样式绘制
cxt.fillStyle = 'hotPink';
cxt.fill();
效果图: