How To Add Mouse Input To Your HTML5 Game
The mouse control really hasn't changed much since its inception, and is still one of the most preferred way of gaming.

Pre-requisites

Setup

Foreword

The tutorials here in general make a basic assumption that you are not a total newbie to programming or basic html. The walkthrough of the codes will zoom in and highlight areas that are crucial to creating the game, but expects some basic understanding of html as well as how to code in Javascript.

Also, in the name of clarity and ease of explanation, optimization of codes is not done.

Getting Started

We will be using a very basic html here with a game canvas object. It links to the javascript file called game.js which will contain some codes to write onto the canvas. It also links to the javascript file constants.js which will contain some static values to initialise the game. For completeness sake, this is how the html file looks like.

edited html

If you have gone through the earlier Set Up tutorial, you'll realise that it is the same. In fact, for subsequent tutorials, we will not be making much modifications to this html file.

For this tutorial, we will not be using any sprites, but rather, use the canvas drawing methods to display a circle at the place where the player clicks. You will just require these 3 simple files as we discussed previously in the Set Up tutorial.

file structure

Step 1 - Detecting the Browser

The reason why we need to first detect the browser is because, different browsers register the mouse clicks in different ways. Add to that the fact that players can be scrolling along your website and that potentially messes up the coordinates of the mouse clicks.

Now, this is where using a package such as jQuery would really help. Such 3rd party javascript packages help you manage cross browser compatibility very well. But since the overall direction of these tutorials here are meant to convey to the simplest codes required to do something, we'll try and cover how to do this without using some external packages.

To detect the browser, I'm just going to borrow these codes which are quite standard. If you google for javascript codes to detect the browser, you should be able to get these codes over the net. I did not write the one below either (this one is actually pretty good as you can detect more info about the browser as well) and you can refer to this StackOverflow link here for the author (thanks! ^_^). But, we need not go in depth on what the codes do here. The output is more important.

//-----------------
//Browser Detection
//-----------------
navigator.sayswho= (function(){
    var N= navigator.appName, ua= navigator.userAgent, tem;
    var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
    if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
    M= M? [M[1], M[2]]: [N, navigator.appVersion, '-?'];

    return M;
})();

var browser;
if (navigator.sayswho[0] == "Firefox")
	browser="f";
else if (navigator.sayswho[0] == "Chrome")
	browser="c";
else if (navigator.sayswho[0] == "Safari")
	browser="s";
else  if (navigator.sayswho[0] == "Microsoft")
	browser="m";
else
	browser="f";

What happens here is that we use a browser variable to register what browser the player is using. A value of "f" would mean Firefox, "c" would mean Chrome, and so on. Just know that at the end of these codes, the browser variable would have contained a letter corresponding to the browser type.

Step 2 - Adding the Canvas Click Event Listener

The way we interact with the game canvas is through something known as events. When the player clicks on the canvas, a click event is actually triggered in the game behaviour. However, if that event is not captured, nothing will happen.

var gameloop, mouseX, mouseY;
mouseX = 300; //default values
mouseY = 300; //default values

gameloop = setInterval(update, TIME_PER_FRAME);			
stage.addEventListener("click", canvasClick, false);

Lines 37 and 38 sets a default position for the variables mouseX and mouseY, which will be used to display a circle.

Line 41 is where we add an event listener to the game stage to listen to the "click" event which will be triggered whenever a left mouse click happens. The event listener will then trigger off the function called canvasClick.

Step 3 - Trigger Off the CanvasClick Function

Look at the codes below. Remember that we have earlier detected what browser the player is using, and assigned it to the variable browser. "f" stands for Firefox, "m" stands for IE, "s" stands for Safari and "c" stands for Chrome. These are the 4 major browsers today.

function canvasClick(event)
{	
	if (browser == "f" || browser == "m")
	{
	mouseX = event.clientX - stage.offsetLeft + document.documentElement.scrollLeft;
	mouseY = event.clientY - stage.offsetTop + document.documentElement.scrollTop;
	}
	else //"s" or "c"
	{
	mouseX = event.clientX - stage.offsetLeft + document.body.scrollLeft;
	mouseY = event.clientY - stage.offsetTop + document.body.scrollTop;
	}
}	

You can see that one key difference is that Firefox and IE handles the scroll of the page differently. Imagine you have a game embedded deeper within the webpage, and the player has to scroll down before he can play. The coordinates detected must thus take into account the offset by which the player has scrolled.

This canvasClick function beautifully takes care of all scrolling and offsets, and gives you 2 variables, mouseX to indicate the x coordinate in the canvas where the click happens, and mouseY to likewise indicate the y coordinate in the canvas of the click.

Later on in your codes, you can simply make use of mouseX and mouseY to check if the click is supposed to do anything. In this example here, we show that each click will create a circle.

//------------
//Game Loop
//------------
function update()
{		
	//Clear Canvas
	ctx.fillStyle = "grey";
	ctx.fillRect(0, 0, stage.width, stage.height);	
	
	ctx.fillStyle = "black";
	ctx.beginPath();
	ctx.arc(mouseX, mouseY, RADIUS, 0 , 2 * Math.PI, false);
	ctx.fillStyle = 'white';
	ctx.fill();
	ctx.lineWidth = 1;
	ctx.strokeStyle = '#003300';
	ctx.stroke();
}

You can see the mouseX and mouseY variables being used in line 68. (If you want more understanding about how to draw the arc which really isn't the focus here, please head over here)

The arc function draws a circle centred at (mouseX,mouseY). These values are constantly updated as the player clicks around in the game canvas. So, with this knowledge, we will see in later game tutorials how we use it to detect it clicking on some game objects, or interacting with buttons, etc.

Until Next Time

You can see how these simple codes help you to understand how the mouse inputs can be read and understood by the game. The codes have been presented in a very flexible way to capture the mouse coordinates, and you can easily plug these into your game projects in future.

Downloads

You can view the demo of this tutorial here (opens in new window).

You can download the files used in this tutorial here.