Reputation: 3942
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
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