HTML5 Canvas - fillRect()vs rect()

Sou*_*abh 19 javascript html5-canvas

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

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();
Run Code Online (Sandbox Code Playgroud)

在Chrome中测试过 | 小提琴

mar*_*rkE 29

fillRect

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

因此,如果您使用多个.fillStyle命令发出多个.fillRect命令,则每个新的rect将填充前面的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
Run Code Online (Sandbox Code Playgroud)

矩形

.rect是canvas的路径命令的一部分.

路径命令是以beginPath()开头的绘图组,并一直持续到发出另一个beginPath().

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

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

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()
Run Code Online (Sandbox Code Playgroud)


Iar*_*hev 5

据我所知,画布有 3 个“矩形”函数:fillRect,strokeRectrect.

ctx.rect(0,0,rectWidth,rectHeight); // create some shape, there is nothing on the canvas yet
ctx.stroke(); // draw stroke of the shape
ctx.fill();   // fill the shape
Run Code Online (Sandbox Code Playgroud)

有两个快捷方式:

ctx.strokeRect(0,0,rectWidth,rectHeight); // shortcut to stroke rectangle
ctx.fillRect(0, 0, rectWidth, rectHeight); // shortcut to fill rectangle
Run Code Online (Sandbox Code Playgroud)

因此,您的fill调用只能填充使用rect.