使用canvas封装一个绘制圆角矩形的方法
阅读该文章,需要具备canvas的相关基础知识,以及了解什么是二次贝塞尔曲线
二次贝塞尔曲线
二次贝塞尔曲线是一种特殊的贝塞尔曲线,它由三个点定义:起始点、控制点,和结束点。这种曲线只能向一个方向弯曲,控制点用来控制曲线的形状。
canvas提供的二次贝塞尔曲线api:quadraticCurveTo(cp1x, cp1y, x, y)
- cp1x, cp1y 为控制点坐标
- x, y 为结束点坐标
- 起始点坐标默认为笔触停留的坐标
圆形矩形绘制逻辑
一个圆形矩形可以由一个矩形、四个圆组成。圆角采用二次贝塞尔曲线绘制。
由图可以,一个圆形矩形的绘制可由五个参数决定:起始坐标x轴、起始坐标y轴、宽、高、圆的半径
- 起始坐标用于确定矩形的位置
如下图,通过(x,y)坐标确定正方形的绘制位置
- 宽、高决定矩形的大小
- 圆的半径决定圆角的弧度
绘制流程
假设起始坐标为(x, y),宽为width,高为height,圆的半径为radius
绘制图
代码实现逻辑
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
canvas {
border: 1px solid black;
}
</style>
</head>
<body onload="draw();">
<canvas id="canvas" width="500" height="500"></canvas>
</body>
<script type="text/javascript">
function draw() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
roundedRect(ctx, 12, 12, 200, 200, 15);
roundedRect(ctx, 53, 53, 49, 33, 10);
roundedRect(ctx, 53, 119, 49, 16, 6);
roundedRect(ctx, 135, 53, 49, 33, 10);
roundedRect(ctx, 135, 119, 25, 49, 10);
}
}
function roundedRect(ctx, x, y, width, height, radius) {
ctx.beginPath();
// 绘制起点
ctx.moveTo(x, y + radius);
// 绘制一条从绘制起点到坐标(x, y + height - radius)的线条
ctx.lineTo(x, y + height - radius);
// 以(x, y + height - radius)为起始点,(x + radius, y + height)为结束点,(x, y + height)为控制点绘制圆角
ctx.quadraticCurveTo(x, y + height, x + radius, y + height);
// 绘制一条从坐标(x + radius, y + height)到坐标(x + width - radius, y + height)的线条
ctx.lineTo(x + width - radius, y + height);
// 以(x + width - radius, y + height)为起始点,(x + width, y + height - radius)为结束点,(x + width, y + height)为控制点绘制圆角
ctx.quadraticCurveTo(x + width, y + height, x + width, y + height - radius);
// 绘制一条从坐标(x + width, y + height - radius)到坐标(x + width, y + radius)的线条
ctx.lineTo(x + width, y + radius);
// 以(x + width, y + radius)为起始点,(x + width - radius, y)为结束点,(x + width, y)为控制点绘制圆角
ctx.quadraticCurveTo(x + width, y, x + width - radius, y);
// 绘制一条从坐标(x + width - radius, y)到坐标(x + radius, y)的线条
ctx.lineTo(x + radius, y);
// 以(x + radius, y)为起始点,(x, y + radius)为结束点,(x, y)为控制点绘制圆角
ctx.quadraticCurveTo(x, y, x, y + radius);
// 通过线条来绘制图形轮廓
ctx.stroke();
}
</script>
</html>
运行图