Minesweeper in Javascript and Canvas

Drawing the menu

The menu screen is drawn with the drawMenu function, which begins by setting the font we wish to use to draw the difficulties names, and creates a variable y with the vertical offset at which we wish to begin drawing the difficulties:

function drawMenu()
{
	ctx.textAlign = 'center';
	ctx.font = "bold 20pt sans-serif";
	ctx.fillStyle = "#000000";
	
	var y = 100;

The difficulties are looped over, and we check to see if the vertical position of the cursor falls on the current difficulty. If it does, we change the colour for this text before rendering its name, and change it back afterwards. Otherwise, it draws with the current fillStyle. We also use the position information to calculate the menuBox start and end values for the difficulty before increasing the y offset ready for the next entry:

	for(var d in difficulties)
	{
		var mouseOver = (mouseState.y>=(y-20) && mouseState.y<=(y+10));
		
		if(mouseOver) { ctx.fillStyle = "#000099"; }
		
		difficulties[d].menuBox = [y-20, y+10];
		ctx.fillText(difficulties[d].name, 150, y);
		y+= 80;
		
		if(mouseOver) { ctx.fillStyle = "#000000"; }
	}

Once the difficulty titles are drawn, we reset the y offset to slightly after the first name will have been drawn, and loop again, this time to show the bestTime values for each difficulty. If there is not a bestTime value yet, we tell the player so.

	for(var d in difficulties)
	{
		if(difficulties[d].bestTime==0)
		{
			ctx.fillText("No best time", 150, y);
		}

Otherwise, we calculate the bestTime minutes and seconds and show the player:

		else
		{
			var t = difficulties[d].bestTime;
			var bestTime = "";
			if((t/1000)>=60)
			{
				bestTime = Math.floor((t/1000)/60) + ":";
				t = t % (60000);
			}
			bestTime+= Math.floor(t/1000) +
				"." + (t%1000);
			ctx.fillText("Best time   " + bestTime, 150, y);
		}

We increase the y offset each loop by the same amount as in the first loop, and we're done with drawing the menu.

		y+= 80;
	}
}
Page loaded in 0.01 second(s).