Resize the Canvas and Coordinates

Free HTML5 Game Tutorial for Beginners: Page 9

Overview Resize Events Detect Resize Events Resize Displays Resize Graphical Coordinates Function resizeData() Summary HTML: Portrait and Landscape Resizing JavaScript: Portrait and Landscape Resizing
Resize Icon

Overview

This tutorial explains how to respond when the player resizes their browser window or reorients their mobile device. This article covers preparing variables which resize the dimensions of game elements, after a resize event. See the Draw and Redraw to the Canvas tutorial for details regarding how to draw with new variables prepared from resize events.

Graphics drawn to the canvas are unlike other elements in HTML. The canvas is a standalone element. You can assign event handlers to the canvas. However when graphics are drawn to various areas of the canvas, user defined code needs to maintain the location of those graphics. You can't assign event handlers to specific graphics rendered to the canvas.

Graphics displaying within the canvas differ from HTML img elements. It's relatively simple to assign an onclick event handler for image elements. However an onclick event handler for the canvas provides the X and Y coordinate location of the click, but not the location of specific objects already drawn to the canvas.

It's necessary to know where game elements are located on the canvas and where the canvas is located in relationship to the Web browser window. In order to know where the canvas is located in relationship to the Web browser, assign resize events. Process and save new dimensions and locations based on the browser size.

Resize Events

Assign an onresize event handler to the Web page's body tag. Resize event handlers allow code to scale the dimensions of the canvas and other HTML elements. Game entities scale up or down to fit the screen. The onresize event fires everytime a mobile device reorients, and everytime the user adjusts the size of the Web browser, on a desktop computer. A device reorients whenever the user rotates, a mobile device, from vertical to horizontal display, or vice versa.

The Surface Game doesn't process resize events when the user scrolls. However capturing scroll events is very important. See the Drag a Sprite example with tutorials to learn about scroll events.

When the screen resizes, adjust the width and height of display elements. The coordinates of each game element will change. Therefore we need to detect the resize event, modify the size of the canvas, and save coordinates to interact with objects on the canvas.

Detect Resize Events

The canvas should resize based on the screen resolution of the current device. For the Surface Game, this tutorial discusses one resize event handler, with two separate resize functions. One function, resizeCanvasMobile(), prepares data for portrait mode displays, where the screen width is less than the screen height. Another function, resizeCanvasDesktop() prepares data for landscape mode displays, where the width is greater than the height of the display screen. The Surface Game reuses similar functions, eventually called from resizeCanvasMobile() or resizeCanvasDesktop(). Both functions call resizeData() and resizeCoords().

Re-using resize functions allows simpler code with more responsive Web design. Responsive design allows one page to render the same game regardless whether the viewing device is a mobile phone or desktop computer.

The following listing demonstrates assigning function resizeCanvas(), to execute when the user rotates a mobile device or resizes a browser window.

 
<body 
 onload="loadGame()" 
 onresize="resizeCanvas()" 
 onunload="stopGame()"
>

Resize Displays

For desktop computers and mobile devices in horizontal orientation, the Surface Game calls resizeCanvasDesktop(). For mobile devices in vertical orientation, the Surface Game calls resizeCanvasMobile(). If the width is greater than the height, call resizeCanvasDesktop(). If the width is less than the height, call resizeCanvasMobile(), as follows.

function resizeCanvas(){

if(window.innerWidth > window.innerHeight){

 resizeCanvasDesktop();
 
}
else {

 resizeCanvasMobile();
 
}
}

For mobile devices, assuming the player holds the device vertically, more height displays. JavaScript allows the canvas to use more width of the screen. Other game elements are located below the canvas. For desktop computers, or devices rotated into landscape mode, the display screen has more horizontal space. Therefore the canvas is located to the left of the screen. Other game elements are located to the right of the canvas.

Both resizeCanvasDesktop() and resizeCanvasMobile() process the same variables, with different dimensions. They assign the width and height of the canvas. Both functions save the Y coordinate of the top box of digits. JavaScript number, iDragBoxT, maintains the Y coordinate for the top row of digits. Both functions save the Y coordinate of the bottom box of digits. JavaScript number, iDragBoxB, maintains the Y coordinate for the bottom row of digits.

Variable iDragBoxT

Number iDragBoxT maintains the Y coordinate for the top box containing a set of draggable digits. The letter T indicates iDragBoxT is above the answer box.

Variable iDragBoxB

Number iDragBoxB maintains the Y coordinate for the bottom box containing a set of draggable digits. The letter B indicates iDragBoxB is below the answer box.

Both Resize Function

Function resizeCoords(), called by either resize function, determines coordinates for each digit. The tutorial Reusable Coordinates explains implementation of resizeCoords(). Function resizeCoords() saves the width and height of square digits to the variable iDimDigit. Number iDimDigit maintains the dimensions of one digit, within either the top box, bottom box, or answer box. Each digit's square. Therefore iDimDigit represents both the height and width of a square which displays one digit.

Both functions also call resizeData(). Function resizeData() prepares a few variables used to resize game elements, then calls a set of functions which accomplish the actual size changes. See Function resizeData() below for more information.

Portrait Resize Function

The following listing includes the entire, resizeCanvasMobile(), function for mobile devices in vertical mode, or Web browsers resized with more height than width. Notice number iW equals 90% of the window's width. Later JavaScript assigns iW to the width of the canvas. Also iSpacer equals one half the width of a digit. The spacer separates rows of boxes in the game along the vertical axis. Coordinates for both the top of the upper drag box and the top of the lower drag box are saved to variables iDragBoxT and iDragBoxB. Details regarding Function resizeData() follow below.

function resizeCanvasMobile(){
 
 var iW = window.innerWidth * 0.90;

 resizeCoords(iW);

 iSpacer = iDimDigit/2;

 iDragBoxT = iDimDigit+iSpacer;

 iDragBoxB = iDimDigit * 3.5;

 iH = new Number(iDimDigit * 4.5);

 resizeData(iW,iH);  

}

Landscape Resize Function

The following listing includes the entire resizeCanvasDesktop() resize function for mobile devices in horizontal mode and desktop computers. Notice number iW equals 50% of the window's width. Later JavaScript assigns iW to the width of the canvas. Therefore the canvas covers 50% or one half, the width of the window. Also iSpacer equals one quarter the width of a digit. The spacer separates rows of boxes in the game. Function resizeData() is discussed below. Numbers iOffsetX and iOffsetY indicate how far the canvas is from the top and left side of the browser window. Offsets are necessary for desktop Web browsers. We need to know where the canvas is located in relationship to the Web browser viewing area. Variable bb is a rectangle representing the canvas dimensions, or bounding box.

function resizeCanvasDesktop(){ 
 
 var iW = window.innerWidth * 0.5; 
 
 iW = new Number(iW); 
 
 resizeCoords(iW); 
 
 iSpacer = iDimDigit/4;
 
 iDragBoxT = iDimDigit+iSpacer;
 
 iDragBoxB = iDimDigit * 2.75;

 iH = new Number(iDimDigit * 3.75); 
 
 resizeData(iW,iH);
 
 iOffsetX = bb.left;
 
 iOffsetY = bb.top; 
 
}

Function resizeData()

Function resizeData() calls functions which redraw the answer box, the answers that are in the answer box, the top row of digits, and bottom row of digits. Function resizeData() uses coordinates calculated by both the mobile and desktop functions, which were just covered. Notice resizeData() calls JavaScript API getBoundingClientRect() to obtain the rectangle which encloses the canvas.

The code for resizeData() is listed below. Parameters iW and iH are assigned to the width and height of the canvas respectively. The Draw and Redraw to the Canvas tutorial explains functionality of drawAnswerBox(), drawAnswers(), and drawDigits(). This tutorial focuses on resizing variables in response to browser resize events. The Draw and Redraw to the Canvas tutorial focuses on redrawing elements based on resized variables.

function resizeData(iW,iH){
 
 if (context != null){
 
  context.canvas.width = iW;

  context.canvas.height = iH; 

  bb = cvs.getBoundingClientRect();

  drawAnswerBox();

  drawAnswers();

  drawDigits(); 

 } 
 
}

Recalculate Graphical Coordinates

Both resizeCanvasMobile() and resizeCanvasDesktop() call resizeCoords() which calls coordsLoad().

The function coordsLoad(...) recalculates the position of each digit based on the current canvas dimensions. See the Reusable Coordinates tutorial for details regarding resizeCoords() and coordsLoad(...).

In a nutshell, coordsLoad(...) divides the number of images by the width of the canvas, then iterates over a list of coordinate objects, modifying the minimum and maximum X position of each coordinate.

Resize events reassign and save coordinates for each interactive game entity on the canvas. Once the coordinates are saved, then it's relatively easy to know when the player taps, touches, or drags, a game entity.

Summary

This tutorial explained how to respond when the player resizes their browser window or reorients their mobile device. This article covered preparing variables which resize the dimensions of game elements, after a resize event. See the Draw and Redraw to the Canvas tutorial for details regarding how to draw with the new variables.

Graphics drawn to the canvas are unlike other elements in HTML. The canvas is a standalone element. You can assign event handlers to the canvas. However, when graphics are drawn to various areas of the canvas, user defined code needs to maintain the location of those graphics. You can't assign event handlers to specific graphics rendered on the canvas.

Graphics displaying within the canvas differ from HTML img elements. It's relatively simple to assign an onclick event handler for image elements. However an onclick event handler for the canvas provides the X and Y coordinate location of the click, but not the location of specific objects already drawn to the canvas.

It's necessary to know where game elements are located on the canvas and where the canvas is located in relationship to the Web browser window. In order to know where the canvas is located in relationship to the Web browser, assign resize events. When the canvas changes dimensions or location within the Web browser, resize events save the new dimensions.

Have fun and love learning! For the next tutorial, tap the image icon containing text which says Next Lesson, or the right pointing arrow at the bottom of the page.

Page 9

Game Tutorial for Beginners was prepared a few years ago. HTML5, CSS3, and JavaScript have improved over time, yet this free course continues to include useful features and long standing software development techniques. Enjoy more projects with free Web & game development tutorials.

Tags

free tutorials, learn web design, learn web programming, read books online free, free ebooks, free books online,free books to read, online books, learn web development, STEM, CSS 3, HTML 5, Web developer, learn to code, learn programming, interactive web design, interactive website design,

Copyright © 2015 Seven Thunder Software. All Rights Reserved.