1

Instead of

<pre>
    <canvas id="theCanvas" width="500" height="500"></canvas>
</pre> 

where I specify the size of the canvas is there a way to make the canvas take up the entire browser window?

devio
  • 36,858
  • 7
  • 80
  • 143
Jared
  • 39,513
  • 29
  • 110
  • 145
  • possible duplicate of [Resize HTML5 canvas to fit window](http://stackoverflow.com/questions/1664785/resize-html5-canvas-to-fit-window) – Jukka Suomela Jun 20 '14 at 14:29

3 Answers3

4

When you are creating a canvas element that spans the entire screen, you are probably going to want to monitor for window resizing events. You can go ahead and use a percentage based style, but you will have to remember to repaint your canvas whenever the window is resized; when a canvas element's dimensions are altered (width or height) the canvas itself is cleared and effectively reset (origin policies are an exception).

I suggest you use something like this:

window.addEventListener(
  'resize', 
  function() { 
    canvas.width = window.innerWidth; 
    canvas.height = window.innerHeight; 
    MyRepaintCallback(); 
  }, 
  false);

There are several considerations for your repaint function beyond the scope of this question. At least, rest assured, knowing that double buffering will likely keep your canvas from flickering between repainting calls.

sdgfsdh
  • 33,689
  • 26
  • 132
  • 245
3
<html>
  <body style="height: 100%; margin: 0;">
    <canvas style="width: 100%; height: 100%;"></canvas>
  </body>
</html>
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • 2
    This is inappropriate, as the width and height attributes of the canvas element are needed for correct scaling. The right solution is to detect the width and height of the window and adjust accordingly to avoid aliasing effects. – dionyziz Dec 29 '12 at 23:11
0

In CSS, set width and height to 100% for html, body (and form if asp.net) tags.

Does not work in older IEs, though.

devio
  • 36,858
  • 7
  • 80
  • 143