Sometimes, we want to fill the whole canvas with a specific color in JavaScript.
In this article, we’ll look at how to fill the whole canvas with a specific color in JavaScript.
Fill the Whole Canvas with a Specific Color in JavaScript
To fill the whole canvas with a specific color in JavaScript, we can set the glovalCompositionOperation
property of the canvas context to 'destination-cover'
.
Then we can set the fillStyle
to the color we want to fill the canvas with.
For instance, we can write:
<canvas width='300' height='300'></canvas>
to add the canvas.
Then we write:
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
ctx.globalCompositeOperation = 'destination-over'
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
We get the canvas with document.querySelector
.
Then we get the context with getContext
.
Then we set the glovalCompositionOperation
property of the canvas context to 'destination-cover'
to add the color behind other elements.
Next, we set fillStyle
to 'blue'
to make the canvas blue.
And then we call fillRect
to add the fill color to the canvas.
Conclusion
To fill the whole canvas with a specific color in JavaScript, we can set the glovalCompositionOperation
property of the canvas context to 'destination-cover'
.
Then we can set the fillStyle
to the color we want to fill the canvas with.