Minesweeper in Javascript and Canvas

Main Game loop

Our main drawGame method checks that the drawing context for the Canvas exists, and then updates the gameTime and calculates the timeElapsed since the method last executed.

function drawGame()
	if(ctx==null) { return; }
	// Frame & update related timing
	var currentFrameTime = Date.now();
	if(lastFrameTime==0) { lastFrameTime = currentFrameTime; }
	var timeElapsed = currentFrameTime - lastFrameTime;
	gameTime+= timeElapsed;

With the gameTime update, we process our game logic with the updateGame method:


We also calculate and update the variables we're using to calculate the frame rate of the game.

	var sec = Math.floor(Date.now()/1000);
		currentSecond = sec;
		framesLastSecond = frameCount;
		frameCount = 1;
	else { frameCount++; }

The whole Canvas is then cleared to a light grey-blue, and the drawing method is called depending on the current gameState.screen value.

	ctx.fillStyle = "#ddddee";
	ctx.fillRect(0, 0, 300, 400);
	if(gameState.screen=='menu') { drawMenu(); }
	else { drawPlaying(); }

Setting the font we wish to use, we then show the frame rate in the top-left corner of the Canvas:

	ctx.textAlign = "left";
	ctx.font = "10pt sans-serif";
	ctx.fillStyle = "#000000";
	ctx.fillText("Frames: " + framesLastSecond, 5, 15);

The lastFrameTime variable is then updated to the time of the current frame (in milliseconds), and we tell the browser to call this method again when it's ready for us to do another animation update before the function is closed.

	lastFrameTime = currentFrameTime;

Mouse position helper

A helper function, realPos, is also used to convert the x, y mouse coordinates in the event listeners from their position on the document to their true position on the Canvas elements, by removing the x, y offset of the Canvas relative to the top-left of the document from the values the events provide:

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.008 second(s).