Search code examples
html5-canvas

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?


Solution

  • 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 🙂.