Solution:How to make canvas 100% of browser window

Monkey Targets Forums/HTML5/Solution:How to make canvas 100% of browser window

richo(Posted 2011) [#1]
I tried using CSS to make the GameCanvas object 100% of the browser window size, however I failed to make it work.

I added the following tag to the CSS section of MonkeyGame.html

#GameCanvas {
height: 100%; width: 100%; border: 1px solid black;
}

I modified the following line of MonkeyGame.html as follows:
<canvas id="GameCanvas" onclick="javascript:this.focus();" tabindex=1></canvas><br>

The result was a blank screen. I'm curious to know why this didn't work (although I'm admittedly not very skilled in HTML5).

I did manage to achieve the effect via a simple modification to main.js (in the window.onload function at the very top of the file)

I added the following lines after line 27, which reads game_console=document.getElementById( "GameConsole":

//add the following two lines for a full-window game canvas
game_canvas.width=window.innerWidth;
game_canvas.height=window.innerHeight;

I'm interested to hear if anyone else has a better way of doing this.


Warpy(Posted 2011) [#2]
Try this:
#GameCanvas {
  position:absolute;
  width: 100%;
  height: 100%;
}


Edit: and of course you should set RESIZEABLE_CANVAS=true on line 4 of main.js


richo(Posted 2011) [#3]
Thank you Warpy - this is a much better way. Being able to resize the canvas in real time is excellent.


QuietBloke(Posted 2011) [#4]
Alternatively I did this in my game:

Replace the top part of the main.js with this :


//Change this to true for a stretchy canvas!
//
var RESIZEABLE_CANVAS=true;

//Start us up!
//

function doResize()
{			
	var canvas = game_canvas;
	canvas=document.getElementById( "GameCanvas" );
	var screenHeight = window.innerHeight;
	var screenWidth = window.innerWidth;
	if (screenWidth*3/4 < screenHeight)
	{
		screenHeight = Math.floor(screenWidth*3/4);
	}
	else
	{
		screenWidth = Math.floor(screenHeight*4/3);
	}
	canvas.style.height = screenHeight;
	canvas.style.width = screenWidth;
	canvas.style.marginLeft = (window.innerWidth-screenWidth)/2;
	canvas.style.marginTop = Math.floor((window.innerHeight-screenHeight)/2);
}

window.onload=function( e ){

	game_canvas=document.getElementById( "GameCanvas" );
	game_console=document.getElementById( "GameConsole" );
	
	if( RESIZEABLE_CANVAS ){
		window.onresize=function() { doResize(); };
	}
		
	doResize();
		
	try{
		bbInit();
		bbMain();
	}catch( ex ){
		if( ex ) alert( ex );
		return;
	}
	
	if( game_runner!=null ){
		game_runner();
	}
}
//Globals


and then in the html file remove the :

<!DOCTYPE html>

at the top of the file.

This makes the assumption the game runs in a 4:3 window and will resize to fill the window while keeping the aspect ratio and centre it.