Languages
[Edit]
EN

JavaScript - how to clear canvas with specific color?

6 points
Created by:
Root-ssh
6253

Simple solution:

// clear from x=0, y=0 on area width * height
// color format: 'yellow', '#FFFF00', 'rgb(255,255,0)' or 'rgba(255,255,0,1)'
context.fillStyle = 'yellow';
context.fillRect(0, 0, canvas.width, canvas.height);

 

Using JavaScript it is possible to clear canvas with specific color in following way.

1. clearRect method 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();">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 format: 'yellow', '#FFFF00', 'rgb(255,255,0)' or 'rgba(255,255,0,1)'
        context.fillStyle = 'yellow';
        context.fillRect(0, 0, canvas.width, canvas.height);
    }

    clearCanvas();
    drawCircle();

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

 

Checkout latest findings & news:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Rockstar community members
Thank you for great work 👍