Jared
Jared

Reputation: 39877

Force canvas element in html to take up the entire window?

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?

Upvotes: 1

Views: 3913

Answers (3)

Charles Pritchard
Charles Pritchard

Reputation: 336

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.

Upvotes: 4

devio
devio

Reputation: 37205

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

Does not work in older IEs, though.

Upvotes: 0

Alex Wayne
Alex Wayne

Reputation: 187004

<html>
  <body style="height: 100%; margin: 0;">
    <canvas style="width: 100%; height: 100%;"></canvas>
  </body>
</html>

Upvotes: 3

Related Questions