Sourabh
Sourabh

Reputation: 8482

HTML5 Canvas - fillRect() vs rect()

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

Tested in Chrome | Fiddle

Upvotes: 21

Views: 25930

Answers (3)

Prathik
Prathik

Reputation: 474

If you want different colors for different path commands, calling beginPath() before each command works.

ctx.beginPath();  
ctx.fillStyle="red";
ctx.rect(10,10,10,10);
ctx.fill()

ctx.beginPath()
ctx.fillStyle="green";
ctx.rect(20,20,10,10);  
ctx.fill()

ctx.beginPath()
ctx.fillStyle="blue";  
ctx.rect(30,30,10,10);  
ctx.fill()

Upvotes: 0

Iaroslav Karandashev
Iaroslav Karandashev

Reputation: 574

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.

Upvotes: 6

markE
markE

Reputation: 105035

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

Upvotes: 30

Related Questions