Creating the Memory Game

Window onload

When the window loads, we'll start by assigning ctx a reference to our Canvas elements 2D drawing content.

window.onload = function()
	ctx = document.getElementById('game').getContext('2d');

We'll also create event listeners for the click and mousemove events that update the mouseState object. The mouse position is converted using the realPos method to the cursor position relative to the top-left of the Canvas element:

	// Event listeners
	document.getElementById('game').addEventListener('click', function(e) {
		var pos = realPos(e.pageX, e.pageY); = pos;
	function(e) {
		var pos = realPos(e.pageX, e.pageY);
		mouseState.x = pos[0];
		mouseState.y = pos[1];

We also need to load our sprites image, from the path given in the spriteSheet.src property. If there is a problem loading, we'll set the ctx global back to null, which will stop further processing. Otherwise, when the loading is done we set the spritesLoaded variable to true so we know the game can begin.

	// Load our spritesheet
	sprites = new Image();
	sprites.onerror = function()
		ctx = null;
		alert("Failed loading sprite sheet.");
	sprites.onload = function()
		console.log("Sprites loaded");
		spritesLoaded = true;
	sprites.src = spriteSheet.src;

We now let the window know that when it's ready, we want to handle drawing with the drawGame function, and close our load method.

Page loaded in 0.008 second(s).