Categories
JavaScript Answers

How to Fill the Whole Canvas with a Specific Color in JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *