Mobile webapp/game developers often face issue to support the application across multiple mobile devices. This is largely because resolutions of mobile are very different.
Take for example iphone. Following are the resolutions of different versions of iphone
iphone <4 320/480.
iphone 4 640/960
iphone 5 640/1136
So now we need a fluid layout that fit across multiple resolutions. So that application can be supported in multiple mobile devices irrespective of the resolution. However, If the application/game is canvas based we need a technique to resize the canvas. Here, I am going to illustrate an awesome technique found from html5 rocks case study. Where we autoresize the canvas with help of wrapper div. Sounds awesome! right. Lets look into the technique.
Technique to resize canvas to fit all multiple resolutions:
Technique:
Wrap the canvas with a div tag and make canvas width and height 100%. Reset the height and width of the div tag via Javascript. Canvas also resizes according to the div tag.
Example:
1) Create a container with the position absolute wrapper div
2) Create the canvas tag and make it as the position absolute and define the height and width of the div as 100%
Html changes:
<div id=”canvasWrapper”>
<canvas id=”canvas” width=”600” height=”700”>
</div>
CSS changes:
#canvasWrapper{
position:absolute;
top:50% (optional)
left:50%(optional)
}
#canvas{
position:absolute; (This is optional)
height:100%;
width:100%
}
Javascript Changes:
Define the window resize handler to control to update the container div based on the view port height and width
$(window).on(“resize”,function(){
var $canvasWrapper = $(‘#canvasWrapper’);
$canvasWrapper.width(document.documentElement.clientWidth);
$canvasWrapper.height(document.documentElement.clientHeight);
});
Reference: http://www.html5rocks.com/en/tutorials/casestudies/gopherwoord-studios-resizing-html5-games/