HTML5 Game - Canvas Clear

Erasing the canvas with clearRect() method

To erase the drawing on canvas, you can use the clearRect() method.

Demo

ResultView the demo in separate window

<!DOCTYPE html>

<html>
  <head>
    <title>Learning the basics of canvas</title>
    <meta charset="utf-8">
    //  w w w.  j a v a2  s  . c  o m
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    
    <script type="text/javascript">
      $(document).ready(function() {  
        let canvas = $("#myCanvas");
        let context = canvas.get(0).getContext("2d");
        
        context.fillStyle = "rgb(255, 0, 0)";
        
        context.fillRect(40, 40, 100, 100);
        
        context.beginPath();
        context.arc(230, 90, 50, 0, Math.PI*2, false);
        context.closePath();
        context.fill();
        
        context.clearRect(230, 90, 50, 50);
      });
    </script>
  </head>
  
  <body>
    <canvas id="myCanvas" width="500" height="500">
      <!-- Insert fallback content here -->
    </canvas>
  </body>
</html>

Related Topics