Skip to content

02-02直线图形-矩形

描边矩形(strokeRect)

绘制描边矩形的步骤

  1. 使用 cxt.strokeStyle 设置属性值(颜色值、渐变色、图案)
  2. 使用 cxt.strokeRect(x, y, width, height) 绘制

注意

属性必须要在方法前定义好,否则画布无法绘制出来

绘制代码

js
cxt.strokeStyle = 'red'
cxt.strokeRect(50, 50, 100, 50)

绘制

html
<canvas id="canvas04-01" width="200"></canvas>
js
const cnv = $$('canvas04-01');
const cxt = cnv.getContext('2d');

cxt.strokeStyle = 'red';
cxt.strokeRect(50, 50, 100, 50)

效果图:

填充矩形(fillRect)

绘制填充矩形的步骤

  1. 使用 cxt.fillStyle 设置属性值(颜色值、渐变色、图案)
  2. 使用 cxt.fillRect(x, y, width, height) 绘制

注意

属性必须要在方法前定义好,否则画布无法绘制出来

绘制代码

js
cxt.fillStyle = 'hotpink'
cxt.fillRect(50, 50, 100, 50)

绘制

html
<canvas id="canvas04-02" width="200"></canvas>
js
const cnv = $$('canvas04-02');
const cxt = cnv.getContext('2d');

cxt.fillStyle = 'hotpink';
cxt.fillRect(50, 50, 100, 50)

效果图:

rect方法绘制矩形

js
cxt.rect(x, y, width, height)

参数说明

x、y是左上角的顶点坐标,width、height是矩形的宽高

rect绘制描边矩形

html
<canvas id="canvas04-03" height="250"></canvas>
js
cxt.strokeStyle = 'red';
cxt.rect(50, 50, 200, 150);
cxt.stroke();
cxt.fillStyle = '#ffe8e8';
cxt.rect(50, 50, 200, 150);
cxt.fill();

rect和strokeRect、fillRect方法的区别

  • rect方法,绘制完成之后不会立马绘制,需要用stroke或者fill才行
  • strokeRect、fillRect方法会立马绘制矩形

清空矩形(clearRect)

js
cxt.clearRect(x, y, width, height)

参数说明

x、y是左上角的顶点坐标,width、height是矩形的宽高

特殊用法-清空画布

如果清空的矩形宽高覆盖整个画布,可以做到清空画布的作用

js
cxt.clearRect(0, 0, cnv.width, cnv.height)

绘制

html
<canvas id="canvas04-04" height="250"></canvas>
js
// 绘制矩形
cxt.fillStyle = 'hotpink';
cxt.rect(50, 50, 200, 150);
cxt.fill();

// 清空矩形
cxt.clearRect(100, 100, 50, 50)
// 清空画布
cxt.clearRect(0, 0, cnv.width, cnv.height)

效果图:

MIT Licensed