矩形是唯一一种可以直接在 2D 上下文中绘制的形状。与矩形有关的方法包括 fillRect() 、strokeRect() 和 clearRect()
这三个方法都能接收 4 个参数:矩形的 x 坐标、矩形的 y 坐标、矩形宽度和矩形高度
绘制灰色实心矩形、透明实心矩形
首先, fillRect() 方法在画布上绘制的矩形会填充指定的颜色。填充的颜色通过fillStyle 属性指定
// 先设置填充色
context.fillStyle = '#ccc';
// 灰色实心矩形
// 1. 语法: x坐标, y坐标, 宽度, 高度
context.fillRect(10, 10, 50, 50);
// 透明实心矩形
context.fillStyle = 'rgba(0, 0, 0, .5)';
context.fillRect(30, 30, 50, 50);
![](https://img.haomeiwen.com/i15804534/ae62d722cded7067.png)
绘制空心的矩形
语法: x坐标, y坐标, 宽度, 高度
// 1. 语法: x坐标, y坐标, 宽度, 高度
context.strokeStyle = 'rgba(255, 0, 0, 1)';
context.strokeRect(100, 10, 50, 50);
context.strokeStyle = 'rgba(255, 255, 0, 1)';
context.strokeRect(120, 30, 50, 50);
![](https://img.haomeiwen.com/i15804534/298fd6cdd85b8f9c.png)
矩形路径
ctx.rect(x, y, w, h);
坐标:(x, y); w: 宽度 , h: 高度
ctx.beginPath();
// 线条颜色
ctx.strokeStyle = 'orange';
// 填充颜色
ctx.fillStyle = 'red';
ctx.lineWidth = 2;
ctx.rect(350, 50, 100, 100);
// 描边
ctx.stroke();
// 填充
ctx.fill();
![](https://img.haomeiwen.com/i15804534/85575d588cfd39c2.png)
绘制弧形
画弧形的语法:
从上一点(起始点) 开始绘制一条曲线,到(x2, y2)位置,并且以(x1, y1)和(x2, y2);为控制点,radius: 弧形半径
ctx.arcTo(x1, y1, x2, y2, radius);
说白话: arcTo会利用起始点 ,(x1, y1), (x2, y2)三个点,所形成的夹角,然后绘制一段与夹角两边相切的圆弧
![](https://img.haomeiwen.com/i15804534/98881a75dd95eec3.png)
弧形可以成为矩形的四个角,使其成为一个圆角矩形
ctx.beginPath();
ctx.lineWidth = 4;
ctx.strokeStyle='blue';
// 起始点
ctx.moveTo(50, 150);
// 左上角
ctx.arcTo(50, 100, 100, 100, 50);
// 右上角
ctx.arcTo(250, 100, 250, 150, 50);
// 右下角
ctx.arcTo(250, 300, 200, 300, 50);
// 左下角
ctx.arcTo(50, 300, 50, 250, 50);
ctx.closePath();
ctx.stroke();
![](https://img.haomeiwen.com/i15804534/fe77ea254c31944f.png)
网友评论