Image 15-Puzzle mechanics

Window onload

When the window has loaded we need to do a few things, so we'll use the window.onload event to do so. First of all, we'll assign the ctx global a reference to the Canvas 2D drawing context, and then set a font for the Canvas.

window.onload = function()
	ctx = document.getElementById('game').getContext('2d');
	ctx.font = "bold 10pt sans-serif";

We'll also add a click event handler for the Canvas element that will update the property with the coordinates of the event relative to the top-left of the Canvas:

	document.getElementById('game').addEventListener('click', function(e) {
		var pos = realPos(e.pageX, e.pageY); = pos;

Loading images

We'll then loop through all of the images we want to load from the imageURLs array. For each entry, we'll begin by creating a new Image object:

	for(var i in imageURLs)
		var img = new Image();

If the image fails to load, we'll alert the user, and clear the ctx variable, essentially ending the script from performing further actions.

		img.onerror = function()
			ctx = null;
			alert("Failed loading image " + this.src);

If the image loads, we'll have the onload event handler log the loading of the image to the developer console, and decrease the loadCount global by 1. If loadCount now equals 0, we know all images have been loaded and we start the first level:

		img.onload = function()
			console.log("Image loaded " + this.src);

Now our event handlers are ready, we begin loading this image by setting its src attribute to the URL we're currently loading, and push the object on to the images array. We also push a value of 0 on to the imageBest array to signify that there is not current best score (lowest move count) for this image, and end the image loading loop.

		img.src = imageURLs[i];

Finally, before closing the onload method, we'll let the browser know the drawGame method will handle drawing when it's ready for us to modify the Canvas.


Mouse position helper

We'll also add in a helper function: this converts the mouse coordinates from their position on the screen to their actual position on the Canvas element:

function realPos(x, y)
	var p = document.getElementById('game');
	do {
		x-= p.offsetLeft;
		y-= p.offsetTop;
		p = p.offsetParent;
	} while(p!=null);
	return [x, y];
Page loaded in 0.007 second(s).