Categories
JavaScript Answers

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

For instance, we write

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

to add a 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 select the canvas with getElementById.

And the we call getContext to get the context.

Next, we set the background color by setting the fillStyle.

And then we call fillRect with 0, 0, canvas.width, canvas.height to draw rectangle that fills the whole canvas with the fillStyle color.

Conclusion

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

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 *