HTML5 画布 - fillRect() 与 rect()

2022-01-17 00:00:00 javascript html5-canvas

在下面的代码中,如果我使用 rect() 然后使用 fill(),第二个 fillStyle 会覆盖第一个中指定的颜色在这两个地方(即,两个矩形都是绿色的)但如果我将第一个 rect() 更改为 fillRect(),则按预期工作(即,第一个矩形是蓝色,第二个是绿色).为什么会这样?我以为 fillRect() 只是 rect() 然后是 fill(),对吧?

In the code below, the second fillStyle overrides the color specified in first one if I use rect() and then fill() in both places (ie, both rects are green) but works as expected (ie, the first rect being blue and second being green) if I change the first rect() to fillRect(). Why is it so? I thought fillRect() was just rect() and then fill(), right?

ctx.translate(canvas.width/2, canvas.height/2);

ctx.fillStyle = "#5A9BDC";
ctx.fillRect(0, 0, rectWidth, rectHeight);
// ctx.rect(0, 0, rectWidth, rectHeight);
// ctx.fill();    

ctx.translate(-canvas.width/2, -canvas.height/2);

ctx.fillStyle = "#31B131";
ctx.rect(0, 0, rectWidth, rectHeight);
ctx.fill();

在 Chrome 中测试 |小提琴

推荐答案

fillRect

.fillRect 是一个独立"命令,用于绘制和填充矩形.

.fillRect is a "stand-alone" command that draws and fills a rectangle.

因此,如果您使用多个 .fillStyle 命令发出多个 .fillRect 命令,则每个新矩形都将被前面的填充样式填充.

So if you issue multiple .fillRect commands with multiple .fillStyle commands, each new rect will be filled with the preceeding fillstyle.

ctx.fillStyle="red";
ctx.fillRect(10,10,10,10);  // filled with red

ctx.fillStyle="green";
ctx.fillRect(20,20,10,10);  // filled with green

ctx.fillStyle="blue";
ctx.fillRect(30,30,10,10);  // filled with blue

矩形

.rect 是画布路径命令的一部分.

.rect is part of the canvas's path commands.

路径命令是绘图组,从 beginPath() 开始,一直持续到另一个 beginPath() 发出.

Path commands are groups of drawings beginning with the beginPath() and continuing until another beginPath() is issued.

在每个组中,只有最后一个样式命令获胜.

Within each group, only the last styling command wins.

因此,如果您在一个路径中发出多个 .rect 命令和多个 .fillStyle 命令,则只有最后一个 .fillStyle 将用于所有 .rect.

So if you issue multiple .rect commands and multiple .fillStyle commands inside a path, only the last .fillStyle will be used on all the .rect's.

ctx.beginPath();  // path commands must begin with beginPath

ctx.fillStyle="red";
ctx.rect(10,10,10,10);  // blue

ctx.fillStyle="green";
ctx.rect(20,20,10,10);  // blue

ctx.fillStyle="blue";  // this is the last fillStyle, so it "wins"
ctx.rect(30,30,10,10);  // blue

// only 1 fillStyle is allowed per beginPath, so the last blue style fills all

ctx.fill()

相关文章