Using the touch screen in your HTML5 games on Android* devices powered by Intel

With the dramatic acceptance rate of smartphones and tablets has come an enormous shift in the way spontaneous experiences are delivered on these touch devices. Native application developers have incorporated touch events to improve the user experience and change the way users interface with their content. Mobile devices such as smartphones and tablets generally have a capacitive touch-sensitive screen to capture interactions made with the user's fingers. As the mobile web evolves to enable increasingly sophisticated applications, web developers need a way to handle these events. For instance, almost any fast game requires players to press several buttons at once, which, in the perspective of a touchscreen, infers multi-touch.

Using the Canvas element in HTML5

In this article we will dive into the touch events API furnished on Android* devices using HTML5. Further, we investigate what kind of applications can be developed and present some best techniques and strategies that make it easier to develop touch-empowered applications. Only recently have mobile applications been able to handle touch events using the HTML5 cross-platform technology. This opens up an entirely new path for making mobile applications more "native-like.” Assuming that we combine this touch event handling with HTML5's new canvas component, we can capture the user's movements and allow them to draw on the canvas component. HTML5 defines the <canvas> component as "a resolution-dependent bitmap canvas which can be used for rendering graphs, game graphics or other visual images on the fly." Per the web definition “Canvas consists of a drawable region defined in HTML code with height and width attributes. JavaScript* code may access the area through a full set of drawing functions.”

Using HTML5 touch events, applications can give users the same great experience that they find with native applications. By offering touch and different gesture-based controls, app developers can help users swiftly traverse through apps or build fun and interactive games.

Developer Guidelines

Let’s plunge in and see how we can use the HTML5 canvas component to capture user touch events.

As stated by W3C, “This specification defines the 5th major version, first minor revision of the core language of the World Wide Web: the Hypertext Markup Language (HTML).”

There are four types of touch events:

  • touchstart
  • touchmove
  • touchend
  • touchcancel

Each is described further below.


This event is triggered when the user places a touch focus on the touch surface; the focus of this event must be a component.


This event is triggered when the user moves a touch point along the touch surface.

The focus of this event must be the same element that established the touchstart event when this touch focus was put on the surface, regardless of the fact that the touch focus has since moved outside the intelligent range of the target component.

Note that the rate we can send touchmove events depends on the speed of the app’s execution, which depends on the hardware it’s running on.


This event is triggered when the user removes a touch point from the touch surface, in addition to cases where the touch point actually leaves the touch surface, such as being dragged off the screen.

The goal of this event must be the similar element that received the touchstart event when this touch point was placed on the surface, regardless of the possibility that the touch focus has since moved outside the region of the target component.


This event is triggered when a touch focus has been disturbed in an implementation particular way. For example, a synchronous event or movement starts from the UI, cancelling the touch, or the touch focus leaves the archive window into a non-report region that is capable of handling user interactions. We might likewise dispatch this event type when the client places more touch focuses on the touch surface than the device or execution is designed to store. In this case the earlier touch object in the touchlist should be evacuated.

To capture touch events and interpret them onto the canvas component, we should first find out how to use the canvas component. There are a couple of things that are top priority when using standard HTML inputs with canvas.

  • Text info fields raise the console (keypad) on mobile devices, blanketing 50% of the screen. To avoid this, we need to ensure that the significant parts of the canvas are not hidden by the console, or pick an alternate sort of input.
  • Buttons with default settings have a tendency to be very small on mobile devices. To make buttons easier to press with a finger, set a smaller viewport or a bigger introductory scale utilizing the <meta> tag, or make the button font bigger with the CSS font style.

Let’s examine the implicit canvas API. We begin by describing the following methods from the canvas API:

  • Context getContext(String contextId);
  • addEventListener()

The getcontext() method is used to acquire the rendering context and its drawing functions. addeventlistener() registers the designated listener on the EventTarget it is called on. The event target may be an element in an archive, the document itself, a window, or any viable item that strengthens events.




A string representing the event type to listen for (touchstart, touchmove, touchend, touchcancel).


Receives a warning when an event of a specified sort happens. This must be an object executing the eventlistener interface, or a JavaScript function.


Assuming that the value is true, this value shows that the user wants to start capturing the touch event. When a capture is initiated, all the specified events will be dispatched to the enlisted listeners before being dispatched to any EventTarget underneath the events in the DOM tree.

Let’s look at some code.

<canvas id= ”touch” width=”150” height=”150”>

Sorry, your browser doesn't support the HTML5 element canvas.


This looks very similar to the <img> component; the main difference is that it doesn't have the <src> and <alt> qualities. The <canvas> component has just two aspects, width and height. If your renderings appear incorrect, try designating your width and height properties explicitly in the canvas characteristics, instead of with CSS. The width and height default to 300 and 150, respectively. The id will be adjusted to initialize the canvas using JavaScript, and the content inside will be used when the browser does not support it.

var cans= document.getElementById('touch');
var canctx = canvas.getContext('2d');

The variable cans acquires the canvas for drawing the graphics objects on, and canctx holds the rendering context. In this case it is a 2d graphics object.

This context encompasses the elementary methods for drawing on the canvas such as arc(), lineto(), and fill().

document.addEventListener("touchstart", startTouchDrawing, true);
document.addEventListener("touchmove", startMoveDrawing, false);
document.addEventListener("touchend", endDrawing, false);
document.addEventListener("touchcancel", cancelDrawing, false);

When users touch/move their fingers on the phone screen, individual events will be created. We have to handle the events and draw the line accordingly. For example, the next piece shows the startMoveDrawing (x, y) function:

function startMoveDrawing (event)
{ event.preventDefault();//To prevent default behavior
var eventTouch, x, y;
eventTouch = event.changedTouches[0];// Array to store previous touch cords,0 is the initial one.
x = eventTouch.pageX;//The first touch for x co-ordinate
 y = eventTouch.pageY;// The first touch for y co-ordinate

OnTouchMoveDraw(x, y);
function OnTouchMoveDraw (x, y)
	if (x || y)
		if ((start_x === -1) || start_y === -1)
			start_x = x;
			starty_y = y;
		drawLine(x, y);

Here, the first contention, that is, "starttouch," is the framework event that calls the user-defined function startTouchDrawing. In the code above preventDefault method anticipates the program’s default behavior and initiates the drawing. start_x and start_y are the previous touch positions. The drawLine(x, y) method draws the line.

function drawLine(x, y) {
	ctx.moveTo(start_x, start_y);
	ctx.lineTo(x, y);

The beginpath() method ensures that we are starting a new path. This begins another path wiping out the present path (if any). If you discover in animation you're getting an interfacing line from the end of your path to the start, it may be you haven't utilized the beginpath() capacity from the start. To generate a path with HTML5 Canvas, we can associate different subpaths. The completion purpose of every new subpath turns into the new setting focus. We can use the lineto(), arcto(), quadraticcurveto(), and beziercurveto() to develop every subpath that makes up our drawing. We can additionally utilize the beginpath() every time we need to start drawing another path (circle, line, rectangle, and so on).

The line is drawn from x, y coordinates passed in the moveTo function to the x, y coordinates passed in the line function.

To conclude, the touch screen has revolutionized the world of computing, and by using the canvas element in HTML5, touch events can be handled with great ease, making developers’ jobs much easier.

HTML5 is a future trend in the world of app development, Intel believes it is important to help experienced developers transition to this cross-platform approach and aid new developers to quickly get up to speed with this exciting new approach so that they can deploy their apps & games on nearly all modern computing platforms. Visit Intel HTML5  and Intel Android page to get more resources for your projects.

Other Related Articles and Resources 

Adding sound to your HTML5 games for Intel® Architecture-based Android* devices
Drawing App using HTML5 Canvas
Building Cross-Platform Apps with HTML5
HTML5 Home Page 

To learn more about Intel tools for the Android developer, visit Intel® Developer Zone for Android.


Intel and the Intel logo are trademarks of Intel Corporation in the U.S. and/or other countries.
Copyright © 2013 Intel Corporation. All rights reserved.
*Other names and brands may be claimed as the property of others.

For more complete information about compiler optimizations, see our Optimization Notice.