Dealing with Browser Resizing, Scrolling, and Zooming
Just because players bring up your game in a browser at a certain size doesn’t mean it’s going to stay that way. Users may resize their desktop browser or may rotate their mobile device to get a better view. Most mobile devices that support HTML5 also enable users to pinch to zoom in and out of the page. You must consider all these actions when you develop a game on mobile.
Handling Resizing
Even if you don’t intend to resize your game when played on the desktop, you should consider adjusting the game to fit the screen on mobile as the player will most likely rotate the device to get a better view of the game.
Listing 6-1 shows what code that adjusts the size of the Canvas element each time the browser is resized would look like. Because there isn’t a game attached to this example, the code that calls the game code to let it know that it’s been resized has been commented out. This is the // Game.resize(newDim); line. You can see this example by running resize.html in the chapter code.
Listing 6-1: resize.html—A self-resizing Canvas
<script> // Wait for the document.ready callback $(function() { var maxWidth = 480; var maxHeight = 440; var initialWidth = $("#game").attr('width'); var initialHeight = $("#game").attr('height'); var handleResize = function() { // Get the window width and height var w = window.innerWidth, h = window.innerHeight, newDim; if(w <= maxWidth) { newDim = { width: Math.min(w,maxWidth), height: Math.min(h,maxHeight) ...
Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.