Sometimes, we want to fill the whole canvas with specific color with JavaScript.
In this article, we’ll look at how to fill the whole canvas with specific color with JavaScript.
How to fill the whole canvas with specific color with JavaScript?
To fill the whole canvas with specific color with JavaScript, we can use the fillStyle
and fillRect
methods.
For instance, we write:
<canvas style='width: 300px; height: 300px'></canvas>
to add the canvas.
Then we write:
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
to get the canvas with document.querySelector
.
And we call canvas.getContext
to get the canvas context.
Next, we set fillStyle
to 'blue'
to set the background color.
And finally, we call fillRect
with 0, 0, canvas.width
, and canvas.height
to fill the whole canvas with the background color.
Conclusion
To fill the whole canvas with specific color with JavaScript, we can use the fillStyle
and fillRect
methods.