Canvas How to - Clear canvas by setting its width and height








Question

We would like to know how to clear canvas by setting its width and height.

Answer


<!-- w  ww  .ja v a  2s  .c  o  m-->



<!DOCTYPE html>

<html>
  <head>
    <script type="text/javascript" 
    src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {  
        var canvas = $("#myCanvas");
        var 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);
        
        canvas.attr("width", canvas.width());
        canvas.attr("height", canvas.height());
        
        context.fillRect(40, 40, 100, 100);
      });
    </script>
  </head>
  
  <body>
    <canvas id="myCanvas" width="500" height="500">
      <!-- Insert fallback content here -->
    </canvas>
  </body>
</html>

The code above is rendered as follows: