Canvas How to - Enlarge canvas to fit the screen size








Question

We would like to know how to enlarge canvas to fit the screen size.

Answer


<!-- w  w w.  j a va2  s .  c o m-->


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    var paint = function() {
        canvas.width  = window.innerWidth;
        canvas.height = window.innerHeight;
        // Draw background
        ctx.fillStyle = 'rgb(255, 255, 255)';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        // Draw rect
        var rect_size=50;
        ctx.fillStyle = 'rgb(0, 0, 255)';
        ctx.fillRect(canvas.width/2-(rect_size/2), canvas.height/2-(rect_size/2), rect_size, rect_size);
    }
    setInterval(paint, 60);
}//]]>  
</script>
</head>
<body>
  <canvas id='canvas'></canvas>
</body>
</html>

The code above is rendered as follows: