Canvas How to - Make canvas fill the browser window








Question

We would like to know how to make canvas fill the browser window.

Answer


<!-- w w  w  .jav a2  s.com-->




<!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");
        
        $(window).resize(resizeCanvas);
        
        function resizeCanvas() {
          canvas.attr("width", $(window).get(0).innerWidth);
          canvas.attr("height", $(window).get(0).innerHeight);
          context.fillRect(0, 0, canvas.width(), canvas.height());
        };
        
        resizeCanvas();
      });
    </script>
  </head>  
  <body>
    <canvas id="myCanvas" width="500" height="500">
      <!-- Insert fallback content here -->
    </canvas>
  </body>
</html>

The code above is rendered as follows: