Categories
JavaScript Answers

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

Spread the love

To fill the whole canvas with specific color with JavaScript, we set the fillStyle and call the fillRect method.

For instance, we write

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

to get the canvas with getElementById.

And then get its context with getContext.

Then we set the fill color by setting the fillStyle.

Finally we call fillRect to fill the canvas with the color by calling with 0, 0, canvas.width, and canvas.height.

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 *