Languages
[Edit]
EN

JavaScript - how to clear canvas with specific color?

6 points
Created by:
Root-ssh
175020

In this article, we would like to show how to clear canvas element using specific color in JavaScript.

To clear canvas with specific color it is necessary to use fillRect() function.

Quick solution:

context.fillStyle = 'yellow';  // color format: 'yellow', '#FFFF00', 'rgb(255,255,0)' or 'rgba(255,255,0,1)'
context.fillRect(0, 0, canvas.width, canvas.height);

 

Reusable function

function clearCanvas(canvas, context, color) {
    context.fillStyle = color;
    context.fillRect(0, 0, canvas.width, canvas.height);
}

Practical example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>
    
    #my-canvas { border: 1px solid gray; }
    
  </style>
</head>
<body>
  <button onclick="drawCircle()">Draw circle!</button>
  <button onclick="clearCanvas('yellow')">Clear canvas!</button>
  <br /><br />
  <canvas id="my-canvas" width="200" height="200"></canvas>
  <script>

    var canvas = document.querySelector('#my-canvas');
    var context = canvas.getContext('2d');

    var xCenter = canvas.width / 2;
    var yCenter = canvas.height / 2;
    var circleRadius = 80;
    
    function drawCircle() {
        context.lineWidth = 5.0;
        context.strokeStyle = '#0000ff';
        context.fillStyle = '#ff0000';
        context.beginPath();
        context.arc(xCenter, yCenter , circleRadius, 0, 2 * Math.PI);
        context.fill();
    }

    function clearCanvas(color) {
        context.fillStyle = color;
        context.fillRect(0, 0, canvas.width, canvas.height);
    }

    clearCanvas('yellow');  // color format: 'yellow', '#FFFF00', 'rgb(255,255,0)' or 'rgba(255,255,0,1)'
    drawCircle();

  </script>
</body>
</html>

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - HTML5 canvas tutorial

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join