fillRect
2023年08月11日
一、认识
ctx.fillRect()
是 Canvas 2D API
绘制填充矩形的方法。当前渲染上下文中的 fillStyle
属性决定了对这个矩形对的填充样式。
这个方法是直接在画布上绘制填充,并不修改当前路径,所以在这个方法后面调用 fill()
或者 stroke()
方法并不会对这个方法有什么影响。
二、语法
ctx.fillRect(x, y, width, height);
-
x
: 矩形起始点的x
轴坐标。 -
y
: 矩形起始点的y
轴坐标。 -
width
: 矩形的宽度。 -
height
: 矩形的高度。
三、场景
3.1 指定宽度矩形
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'green';
ctx.fillRect(0,0,200,100);
3.2 填充完整画布
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'green';
ctx.fillRect(0,0,canvas.width,canvas.height);