JavaScript Answers

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

Spread the love

To fill the whole canvas with a specific color using JavaScript, you can use the fillRect() method of the canvas context.

To do this, we write:

<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Fill Canvas with Color</title>
  <canvas id="myCanvas" width="400" height="300"></canvas>

    // Get reference to the canvas element
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');

    // Specify the color you want to fill the canvas with
    var fillColor = '#ff0000'; // Red color, you can change this to any color

    // Set the fill color
    ctx.fillStyle = fillColor;

    // Fill the entire canvas with the specified color
    ctx.fillRect(0, 0, canvas.width, canvas.height);

In this example, we’re using the fillRect() method to draw a filled rectangle that covers the entire canvas.

We set the fill color using ctx.fillStyle, and then we use ctx.fillRect() to draw a rectangle starting at coordinates (0, 0) with a width equal to the canvas width and a height equal to the canvas height.

Adjust the fillColor variable to specify the color you want to fill the canvas with.

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 *