Clear the HTML5 canvas

Example of how you can clear the HTML5 canvas.
<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="600" height="300"></canvas>
      <div id="buttons">
        <input type="button" id="clear" value="Clear the canvas">
      </div>
    <script>

    var canvas = document.getElementById('myCanvas'); 
    var ctx = canvas.getContext('2d'); 

        ctx.fillStyle = 'red';
        ctx.beginPath(); 
        ctx.arc(300, 150, 50, 0 * Math.PI, 2 * Math.PI); 
        ctx.fill();
        
        var button = document.getElementById('clear');
        
        button.addEventListener('click', function() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
        }, false);
        
   </script>
  </body>
</html>   

Responses

0 Replies