user269867
user269867

Reputation: 3942

How to draw rectangles with different colors on a canvas?

The following code draws two rectangles:

const demoCanvas = document.getElementById('canvas-demo').getContext('2d');

window.onload = function() {
  demoCanvas.fillStyle = 'red';
  demoCanvas.rect(10, 10, 60, 60);
  demoCanvas.fill(); // first rectangle

  demoCanvas.fillStyle = 'blue';
  demoCanvas.rect(10, 110, 60, 60);
  demoCanvas.fill();
}
<canvas id="canvas-demo" width="300" height="300">

The output is two blue rectangles. I tried adding begin and close path as well, but the rectangles take only one color for some reason. In this case, it's blue. How can I fix this?

Upvotes: 0

Views: 53

Answers (1)

user17570160
user17570160

Reputation:

Here is the solution:

const demoCanvas = document.getElementById('canvas-demo').getContext('2d');

window.onload = function() {

    demoCanvas.beginPath();
    demoCanvas.fillStyle = 'red';
    demoCanvas.rect(10, 10, 60, 60);
    demoCanvas.fill();
    demoCanvas.closePath();

    demoCanvas.beginPath();
    demoCanvas.fillStyle = 'blue';
    demoCanvas.rect(10, 110, 60, 60);
    demoCanvas.fill();
    demoCanvas.closePath();
                
}
<canvas id="canvas-demo" width="300" height="300">

Hope you found this helpful, Cheers 🙂.

Upvotes: 1

Related Questions