Reusable Coordinates

Free HTML5 Game Tutorial for Beginners: Page 8

Overview One Coordinate Coordinate Array Find Coordinates Modify Coordinates Summary Source: One Coordinate Source: Coordinate Array
Coordinates on a Graph


This article demonstrates how to implement reusable code for graphical coordinates on the HTML5 canvas. The JavaScript presented here has multiple uses including resizing graphics when a mobile device changes orientation, and locating graphics with a mobile touch point or mouse pointer.

This tutorial explains how to prepare a list of screen coordinates, which fit evenly within the size of any display. This article includes a function which resizes coordinates of graphics regardless of the mobile device, orientation, or computer.

Coords and Coordinate Array

This tutorial demonstrates how to make one class called Coord, and another file called coord-list.js. JavaScript file coord-list.js operates on an Array of Coord. The classes work together to allow efficient display of an Array of graphics on the canvas.

One Coordinate: Constructor Coord()

Coordinates for one entity in one dimension are stored within a Coord object.

Coord.js includes a constructor. A constructor is a special function used to create one reference of a Coord object. A constructor must have the same name as the type of object it creates. In this case the constructor's name is Coord. A constructor must reside in a file with the same name. In this case the constructor is implemented in Coord.js. The following listing includes the entire Coord() constructor.

function Coord(mn, mx, i) {
 this.min = new Number(mn);

 this.max = new Number(mx);

 this.idx= new Number(i); 


Every Coord includes a min, max, and idx field. The min and max fields are the ranges where one graphic is located. The Coord object keeps track of the location of an individual graphic. The idx field indexes into an array of graphics.

For example, assume the user touched point x = 100. We want to find a Coord object in an array of Coord which might display under that particular touch point. If a Coord located in the array had properties min = 90 and max = 110 then that Coord reference would match. 100 is in between 90 and 110.

The Surface Game uses Coord to scale graphics along the screen width. The min and max fields represent X values for the left and right edges of a graphic. However the code could apply to any individual axis at a time. For example the min and max fields could apply to Y values or even Z values in a three dimensional rendering.

Coordinate List

Functions which operate on an Array of Coord are implemented in the JavaScript file coord-list.js. The file coord-list.js, doesn't require a constructor.

coord-list.js only accomplishes two tasks. First, coord-list.js creates or modifies the location of each Coord in an Array of Coord, based on the parameters provided to function coordsLoad(...). Second, coord-list.js returns the Coord which is located under the mouse or touch point passed as a parameter to function coordFind(...).

Modify Coordinates: Function resizeCoords()

When the window resizes or the user rotates a mobile device, a resize event handler executes. The tutorial Resize the Canvas and Coordinates explains resize events. The resize event calls functions, resizeCoords() defined within file surface-game-canvas.js, regardless whether the display screen's in portrait or landscape mode. Function resizeCoords() also calls function coordsLoad().

Number iDimDigit represents the width and height of one square digit. Array aCoords maintains an array of coordinates for the top row of draggable digits. Array aCoordsB maintains an array of coordinates for the bottom row of draggable digits. The entire resizeCoords() function follows.

Variable iDimHalf is calculated from the maximum width of the first Coord in the array. Line iDimDigit = aCoords[0].max; returns the width of one digit. Variable iDimDigit represents the width of a digit scaled to fit evenly across the canvas along with four other digits. Line iDimHalf = iDimDigit/2; saves the width of one half of one digit. Code uses the dimensions of scaled digits in other functions.

Current JavaScript standards allow use of the const keyword to prepare a JavaScript constant. However, some browsers have yet to handle const keywords. If the Surface Game doesn't run, try changing constant keywords from const to var. This tutorial identifies variables which are applied as constants, with upper case letters. JavaScript file surface-game-canvas.js assigns const ROW_COUNT the value of five. Each row includes no more than five digits.

// max  images per row to display [0..4].
const ROW_COUNT	= new Number(5);
function resizeCoords(iW){
 // function coordsLoad(...)
 // is defined in coords.js.
 aCoords = coordsLoad(

 aCoordsB = coordsLoad(

 iDimDigit = aCoords[0].max;

 iDimHalf = iDimDigit/2; 

Function coordsLoad()

Function coordsLoad(...) executes when the game first loads, whenever the player resizes a desktop browser, or the player reorients a mobile device.

Function coordsLoad(...) includes the following parameters. The first parameter, iD, represents the maximum dimension of the display screen. The second parameter, aCoords, is an array of coordinates of type Coord. If aCoords equals null then function coordsLoad(...) creates an array of Coord. The last parameter, n, is the starting index for the array of Coord. For example the top array represents digits zero through four. Therefore n equals zero for the top array of digits. The bottom array represents digits five through nine. Therefore n equals five for the bottom array of digits.

The following listing includes the entire coordsLoad(...) function. The top line in the following listing displays the constant value, assigned to variable COL_COUNT, before executing function coordsLoad(...).

coord-list.js includes a fixed sized number constant called, COL_COUNT, which determines how many divisions to define within an Array of Coord.

Constant, COL_COUNT, equals 5 for the Surface Game. The Surface Game includes digits zero through nine. Digits zero through four display on the top row. Digits five through nine display on the bottom row. Five graphics display along the top row and five graphics display along the bottom row.

// Max images per row.
// [0..4] == 5.
const COL_COUNT = new Number(5); 

@param ID {Number}:
Maximum display screen dimension. 

@param aCoords {Array}:
Containing type Coord. 

@param n {Number)
Starting index from array aCoords.
function coordsLoad(iD,aCoords,n){
 var maxAbs = new Number(iD);

 var nMin = 0;

 var nDivision = new Number(maxAbs/COL_COUNT); 

 try {
  if (aCoords == null){
   aCoords = new Array(COL_COUNT);

   for (var i = 0; i < COL_COUNT; i++){
    aCoords[i] = new Coord();

    aCoords[i].min = new Number(nMin);

    aCoords[i].max = new Number(nMin + nDivision);
    // This loop creates and
    // assigns the idx property.
    aCoords[i].idx = new Number(i + n);

    nMin += nDivision;   


  return aCoords;


 else {
 for (var i = 0; i < COL_COUNT; i++){ 
  aCoords[i].min = new Number(nMin);

  aCoords[i].max = new Number(nMin + nDivision); 

  nMin += nDivision;


 return aCoords;


catch (err){ 
viewDebug("loadCoords() error:"+err.toString());


return null;


Find Coordinates: Function coordFind()

Function coordFind(...) returns a Coord object whose min and max fields bracket the parameter number nFind. In other words the value of number nFind is greater than or equal to property min and less than or equal to property max.

The first parameter, number nFind, is one coordinate of a touch or mouse point. This second parameter aCoords is an array of Coord.

For example assume the player touched the canvas at the point X = 6. Array aCoords contains a set of five Coord. Each Coord covers four units. The first Coord starts at X = 0 and ends at X = 4. The first Coord.min = 0 and Coord.max = 4. The second Coord starts at X = 4 and ends at X = 8. X = 6 is in between 4 and 8. Therefore the second Coord in the array was selected by the player. The idx value of the Coord represents the digit that was tapped. Variable idx is an integer index into an array of images representing digits.

The following listing includes the entire coordFind(...) function.

* @param nFind {Number}
* @param aCoords {Array} of Coord
function coordFind(nFind,aCoords){ 

 for (var i = 0; i < COL_COUNT; i++){  

  if (nFind >= aCoords[i].min && nFind <= aCoords[i].max){

   return aCoords[i];   


 return null;



This tutorial demonstrated how to implement reusable code for graphical coordinates on the HTML5 canvas. The JavaScript code has multiple uses including resizing graphics when a mobile device changes orientation, and locating graphics with a mobile touch point or mouse coordinate.

This article explained how to prepare a list of screen coordinates which fit evenly within the size of any display screen. This section included a function which can resize coordinates of graphics regardless of the mobile device, orientation, or computer.

Tutorials Resize the Canvas and Coordinates, Locate Graphics on the Canvas by Touch, and Draw and Redraw to the Canvas demonstrate use of Coord and coord-list.js.

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 8

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.


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.