Snake Game

Onload calculations and setup

When the page loads we need to update our pointer to the Canvas 2D drawing context (ctx), and calculate the offsetX, offsetY to position the map centrally on the Canvas when playing.

We'll also create event listeners for the mouse and the arrow keys, and the F key (for toggling frame rate visibility). Additionally, we'll let the window know that when it's ready to draw to the Canvas we'll handle it with the drawGame function.

window.onload = function()
	// Create a reference to the Canvas 2D drawing context
	ctx = document.getElementById('game').getContext('2d');

	// Calculate the offsets needed to centre our map on the
	// Canvas
	offsetX = Math.floor((document.getElementById('game').width -
		(gameState.mapW * gameState.tileW)) / 2);
	offsetY = Math.floor((document.getElementById('game').height -
		(gameState.mapH * gameState.tileH)) / 2);
	document.getElementById('game').addEventListener('click', function(e) {
		// When the Canvas is clicked on, find the position
		// of the mouse click and record a click event in the
		// mouseState object
		var pos = realPos(e.pageX, e.pageY); = pos;
	function(e) {
		// When the mouse is moved on the Canvas, find the true
		// cursor position and update the mouseState x,y accordingly
		var pos = realPos(e.pageX, e.pageY);
		mouseState.x = pos[0];
		mouseState.y = pos[1];
	window.addEventListener('keydown', function(e) {
		// If an arrow key is pressed, update the direction (dir)
		// property accordingly.  If the F key is pressed, toggle
		// the visibility of the frame rate counter
		if(e.keyCode==38) { gameState.dir = 0; }
		else if(e.keyCode==39) { gameState.dir = 1; }
		else if(e.keyCode==40) { gameState.dir = 2; }
		else if(e.keyCode==37) { gameState.dir = 3; }
		else if(e.keyCode==70) { showFramerate = !showFramerate; }
	// When the Canvas is ready to draw, call our drawGame method	

Our offsetX, offsetY values are calculated by subtracting the width/height of the map (in pixels) from the width/height of the Canvas (in pixels), and dividing the result by 2.

Page loaded in 0.009 second(s).