Home » Tutorials » JavaScript » Game Development: Mouse and Touch Event Detection

Game Development: Mouse and Touch Event Detection

Game Development: Mouse and Touch Event Detection

  • Stumble it!
  • Share

The Full Series

Welcome to the first tutorial of ‘HTML5 Canvas Game Development’! In this tutorial, you will learn the technique of detecting mouse and touch events for building a game for PC users and touch devices users.

View Demo

Getting Started

First of all, let’s install the viewport meta tag for your document.

<meta name="viewport" content="width=device-width, user-scalable=no">

This will script will force your page fit nicely on touch devices, such as iPhone, iPad and Android. If you want to learn more about viewport meta tag, please read our previous article here – Viewport Meta Tag For Mobile Devices.

Create a canvas for the page and assign an id for it. Note: For best practice, please provide fallback content, if user browser is not supported.

<canvas id="canvas" height="200" width="300" style="background-color:black">
	Sorry, your browser doesn't support canvas technology.
</canvas>

If you are new to HTML5 Canvas, please read our previous article – HTML5 Canvas For Absolute Beginners before proceed.

All rights, we have done the basic structure for our page. Now, it’s time to talk about the JavaScript that using to detect the mouse and touch events.

JavaScript Section

Defines 5 global variables:

var canvas;
var ctx;
var canvasX;
var canvasY;
var mouseIsDown = 0;

Create an initial function, assign canvas element to the variable that we defined earlier, install event listener on the canvas to listen to user’s mouse movement and finger movement.

function init() {
	canvas = document.getElementById("canvas");
	ctx = canvas.getContext("2d");
	
	canvas.addEventListener("mousedown",mouseDown, false);
	canvas.addEventListener("mousemove",mouseXY, false);
	canvas.addEventListener("touchstart", touchDown, false);
    canvas.addEventListener("touchmove", touchXY, true);
    canvas.addEventListener("touchend", touchUp, false);
	
	document.body.addEventListener("mouseup", mouseUp, false);
    document.body.addEventListener("touchcancel", touchUp, false);
		
}

Next, let’s create the functions that will be called according to the event listeners.

function mouseUp() {
    mouseIsDown = 0;
    mouseXY();
}

function touchUp() {
    mouseIsDown = 0;
    showPos();
}

function mouseDown() {
    mouseIsDown = 1;
    mouseXY();
}
 
function touchDown() {
    mouseIsDown = 1;
    touchXY();
}

As you can see above, another functions such as mouseXY, touchXY and showPos will be called respectively. So let’s create those function as shown below:

function mouseXY(e) {
    e.preventDefault();
    canvasX = e.pageX - canvas.offsetLeft;
    canvasY = e.pageY - canvas.offsetTop;
    showPos();
}

function touchXY(e) {
    e.preventDefault();
    canvasX = e.targetTouches[0].pageX - canvas.offsetLeft;
    canvasY = e.targetTouches[0].pageY - canvas.offsetTop;
    showPos();
}

function showPos() {
    ctx.font="14px Arial";
    ctx.textAlign="center";
    ctx.textBaseline="middle";
    ctx.fillStyle="rgb(255,255,255)";
    var str = canvasX + ", " + canvasY;
    if (mouseIsDown) str = str + " down";
    if (!mouseIsDown) str = str + " up";
    ctx.clearRect(0,0, canvas.width,canvas.height);
    ctx.fillText(str, canvas.width /2, canvas.height / 2, canvas.width - 10);
}

Description

mouseXy, touchXY:
This function used to get the current mouse cursor / finger position using pageX, pageY properties then subtract the canvas’s offsetLeft and offsetTop properties. Then display the current position on canvas using showPos function.

showPos
Inside the showPos function, we defined the font size, family, color that going to use for displaying the current position, and align the text in center. Note: “ctx.clearRect(0,0, canvas.width,canvas.height);” must be included, so that the text always be cleared.

Lastly, the most important thing, before get everything work is to run your init function when window is load.

window.addEventListener('load', init, false);

That’s all! Here is the final piece of code for you to copy and play around it!

<!DOCTYPE html>
<head>
<title>Detection of Mouse and Touch Events | onlyWebPro.com</title>
<meta name="viewport" content="width=device-width, user-scalable=no">
<script type="text/javascript">
window.addEventListener('load', init, false);

var canvas;
var ctx;
var canvasX;
var canvasY;
var mouseIsDown = 0;

function init() {
	canvas = document.getElementById("canvas");
	ctx = canvas.getContext("2d");
	
	canvas.addEventListener("mousedown",mouseDown, false);
	canvas.addEventListener("mousemove",mouseXY, false);
	canvas.addEventListener("touchstart", touchDown, false);
    canvas.addEventListener("touchmove", touchXY, true);
    canvas.addEventListener("touchend", touchUp, false);
	
	document.body.addEventListener("mouseup", mouseUp, false);
    document.body.addEventListener("touchcancel", touchUp, false);
		
}

function mouseUp() {
    mouseIsDown = 0;
    mouseXY();
}

function touchUp() {
    mouseIsDown = 0;
    showPos();
}

function mouseDown() {
    mouseIsDown = 1;
    mouseXY();
}
 
function touchDown() {
    mouseIsDown = 1;
    touchXY();
}

function mouseXY(e) {
	e.preventDefault();
    canvasX = e.pageX - canvas.offsetLeft;
    canvasY = e.pageY - canvas.offsetTop;
    showPos();
}

function touchXY(e) {
    e.preventDefault();
    canvasX = e.targetTouches[0].pageX - canvas.offsetLeft;
    canvasY = e.targetTouches[0].pageY - canvas.offsetTop;
    showPos();
}

function showPos() {
    ctx.font="12px Arial";
    ctx.textAlign="center";
    ctx.textBaseline="middle";
    ctx.fillStyle="rgb(255,255,255)";
    var str = canvasX + ", " + canvasY;
    if (mouseIsDown) str = str + " down";
    if (!mouseIsDown) str = str + " up";
    ctx.clearRect(0,0, canvas.width,canvas.height);
    ctx.fillText(str, canvas.width /2, canvas.height / 2, canvas.width - 10);
}
</script>
</head>
 
<body>
<canvas id="canvas" height="200" width="300" style="background-color:black">
	Sorry, your browser doesn't support canvas technology.
</canvas>
</body>
</html>

View Demo


  • How To Create jQuery Password Strength Indicator in 10 Minutes!
  • Make A jQuery Sticky Header In 5 Minutes
  • Create Sequential Animations in jQuery

Android, iOS Development Tutorials