如何在 canvas 上绘制不同颜色的矩形?

How to draw rectangles with different colors on a canvas?

以下代码绘制两个矩形:

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">

输出是两个蓝色矩形。我也尝试添加开始和关闭路径,但出于某种原因,矩形只采用一种颜色。在这种情况下,它是蓝色的。我该如何解决这个问题?

解决方法如下:

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">

希望这对您有所帮助,干杯。