Locate Graphics on the Canvas by Touch

Free HTML5 Game Tutorial for Beginners: Page 11

Overview Locate Graphics Detect Touch and Tap Summary Source: Assign Touch Listener Source: Assign Mouse Listener Source: Respond to Mouse Source: Process Touch and Mouse
Touch Icon

Free Online Game Development Course: Design with HTML5

Locate Graphics By Touch or Mouse Movement

For Mobile Devices & Desktop Computers

Overview

This tutorial explains how to respond to touch and mouse movement over the HTML5 canvas element. This article explains how to assign a touchmove event listener for mobile devices, along with an onclick event listener for full computers.

This lesson demonstrates how the Surface Game determines which element, on the canvas, the player selected.

The Surface Game makes use of the Coord class and coord-list.js JavaScript file. Please see the Reusable Coordinates tutorial for details regarding the Coord class, and coord-list.js JavaScript.

Graphics drawn to the canvas, are unlike other elements in HTML. The canvas is a standalone element. Developers can assign event handlers to the canvas. However graphics drawn to various areas of the canvas, require user defined code to maintain the location of graphics on the canvas.

Graphics displaying within the canvas, differ from HTML img elements. It's relatively simple to assign an onclick event handler for img elements. However currently we can't assign onclick handlers to specific elements which display on the canvas. The entire canvas can have an onclick handler, but not individual graphics rendered to the canvas.

The Surface Game keeps track of graphical coordinates in an array. When the display resizes, update data within the coordinate array. See Resize the Canvas and Coordinates tutorial for more details.

Locating Elements on the Canvas

Perhaps locating elements on the canvas, presents the most challenging aspect of HTML5 game development. The size of the canvas can vary depending on the viewing device or computer. The size of the canvas can change during game play. For example the player might rotate the device, or change dimensions of the browser window. Therefore the size and location of every game object may change at any time.

Save and update coordinates for each size and resize of the screen. When the player touches an area of the canvas, access a list of coordinates to determine which game entity the player selected.

Detect Touch and Mouse Events

For mobile devices declare a touchmove event listener in JavaScript.

The touchmove event object's targetTouches property contains a list of Touch objects. The first Touch object in the list, includes properties defining the location of the current touch point on the screen. Touch properties pageX and pageY represent the X and Y coordinates of the current touch point. In other words, pageX and pageY tell us where the player tapped or touched the browser window.

The following listing demonstrates adding an anonymous touchmove event listener to the canvas. The anonymous event listener calls Surface Game's drawTapGraphic() function.

The anonymous touchmove event listener passes the pageX and pageY touch coordinates to drawTapGraphic().

cvs = document.getElementById('cv');
...		
cvs.addEventListener
(

'touchmove', 
 
function (e) 
{

e.preventDefault();			
	 
if (e.targetTouches.length > =  1) {

var t1 = e.targetTouches[0];

drawTapGraphic
(
 t1.pageX,
 t1.pageY
);
}
},

false
);	

For desktop computers assign an onclick event handler in HTML. The following short listing demonstrates assigning mouseMoveCanvas() to respond when the player taps the canvas.

		
<canvas 
id="cv"  
onclick="javascript:mouseMoveCanvas(event)">

Canvas is not supported in your browser.

</canvas>	
		

For desktops define a function which translates coordinates from the Web page to the canvas. The X and Y coordinates received from an onmousemove event handler represent the entire browser window. We need to know the canvas location in relationship to the upper left corner of the browser window.

The mobile version of the Surface Game places the canvas's upper left corner at the browser window's upper left corner. Therefore translating coordinates from the Web page to the canvas is not necessary for mobile touchmove events.

However desktop MouseEvent objects require offsets between the browser's top left corner and the canvas's top left corner. The Interactive Sprite Movement example with tutorial explains function translateToCanvasCoords(). The following listing includes the entire mouseMoveCanvas() function.

Once again function drawTapCanvas() is called with X and Y coordinates representing the current touch point.

function mouseMoveCanvas(ev){

ev.preventDefault();

var a = translateToCanvasCoords
(

ev.clientX, 

ev.clientY

);

drawTapGraphic
(
a[0],
a[1]
);

}
	

Find a Graphic

In response to touchmove and mousemove events the Surface Game calls drawTapGraphic(iX,iY) for both mobile and desktop games.

Function drawTapGraphic() determines if the player touched within the top row of draggable digits, the bottom row of draggable digits, or the answer box.

If the player touched within the top or bottom row of draggable digits, call function coordFind(). If the player touched within the answer box, call function drawAnswerDigit().

Function coordFind() iterates through a list of coordinates looking for an object. Function coordFind(iX,aCoords) looks for the object whose min and max X coordinates, are boundaries for the parameter iX. In other words if iX is in between min and max, then we found the object the player tapped. Function coordFind(iX,aCoords) returns either a Coord reference or null. A return value of null indicates the player did not tap an element in the list.

When coordFind() returns a valid Coord object, then highlight the selected area. Call the function drawHighlight(). See tutorial Highlight Graphics on the Canvas for details regarding highlighting game entities.

The following listing includes pertinent portions of the drawTapGraphic(iX,iY) function. First determine if the player touched the top or the bottom drag box. Surface Game displays two horizontal areas with selectable graphics. The variable iDragBoxT represents the bottom of the top horizontal section. The variable iDragBoxB represents the top of the botttom horizontal section.

If the touch point's less than iDragBoxT or greater than iDragBoxB then find the currently selected digit. If the touch point's less than iDragBoxT or greater than iDragBoxB, then the player touched within the top or the bottom box of draggable digits. Call coordFind() if the player touched within either area. Assign the drag box's top Y parameter to iHighlightY. Finally call function drawHighlight() to provide user feedback.

If the touch point's within the answer box, then draw the digit to the answer box with a call to drawAnswerDigit().

function drawTapGraphic(iX,iY){
 
try{ 
  
if (iX < 0) 
 iX = iOffsetX;
  
if (iY < 0) 
 iY = iOffsetY; 
  
if (iY <= iDragBoxT){
   
 coord = coordFind(
  iX,
 aCoords
 );
   
 iHighlightY = iSpacer;
   
}
  
else if (iY >= iDragBoxB){
   
 coord = coordFind(
  iX,aCoordsB
 ); 
   
 iHighlightY = iDragBoxB; 
   
}
  
if (coord != null){
   
// Draw graphic inside the answer box:
if (isInsideShape(iX,iY,shapeAnswerBox)== true){
    
 drawAnswerDigit(coord.idx);
    
}
   
// Draw graphic tapped:
else if (isInsideShape(iX,iY,shapeAnswerBox) == false){

 redraw();

 drawHighlight();

}
   
}
  
}
 
catch (err){
  
viewDebug("drawTapGraphic(): "+err.toString());
 
}
 
}

Summary

This tutorial explained how to respond to touch and mouse movement on the HTML5 canvas element. This lesson explained how to assign a touchmove event listener for mobile devices, along with an onclick event listener for full computers.

This tutorial explained one method to determine elements under touch locations on the canvas. This article demonstrated how the Surface Game finds selected objects on the canvas.

This article referenced supporting functions for the Surface Game. See the Reusable Coordinates and Highlight Graphics on the Canvas tutorials for Surface Game details. See the Interactive Sprite Movement example with tutorials, for details regarding multiple event listeners and canvas sprites.

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.

Previous Page Next Page
Copyright © 2015 Seven Thunder Software. All Rights Reserved.