HTML5 Canvas - fillRect() vs rect()

fillRect

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

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.

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.

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()

As I know there are 3 "rect" functions for canvas: fillRect, strokeRect and rect.

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

There are two shortcuts:

ctx.strokeRect(0,0,rectWidth,rectHeight); // shortcut to stroke rectangle
ctx.fillRect(0, 0, rectWidth, rectHeight); // shortcut to fill rectangle

So, your fill invocation could fill only your shape created with rect.