How to fill the whole canvas with specific color with JavaScript?

Spread the love

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 use the fillRect method.

For instance, we write

<canvas width="300" height="150" id="canvas"> </canvas>

to add the canvas.

Then we write

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);

to get the canvas with getElementById.

We get the context with getContext.

Then we set the background color to 'blue' by setting fillStyle.

And then we apply the background color with fillRect.

Conclusion

To fill the whole canvas with specific color with JavaScript, we use the fillRect method.

Leave a Reply

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