Home > HTML5 > HTML5 Canvas Example :A simple Snake Game

HTML5 Canvas Example :A simple Snake Game


I will explain basics of HTML5 Canvas with an Example.

You will learn How to develop Snake Game using HTML5 Canvas.If you familiar with JQuery then it’s very easy.

HTML5 Code:

These are the main elements in html.

  • One <canvas> element for Snake Game.
  • Two <audio> tags for GamePlay and GameOver
  • One <p> Tag for displaying Scores.
  • And buttons for Play,pause,SoundOFF,SoundON.
<canvas id="canvas" width="500" height="300">OOPS.. Upgrade your Browser</canvas>
<audio id="GamePlay" loop="loop" autoplay="autoplay">       
            <source src="GameGng.mp3" type="audio/mpeg" />
            Your browser does not support HTML5 audio.
		<audio id="GameOver">       
            <source src="GameOver.mp3" type="audio/mpeg" />
            Your browser does not support HTML5 audio.
		<audio id="SnakeFood">       
            <source src="SnakeEating.mp3" type="audio/mpeg" />
            Your browser does not support HTML5 audio.
		<strong><p id="Score"></p></strong>		
<button id="pause"><img src="pause.jpg" alt="Pause"/></button>
<button id="play"><img src="play.jpg" alt="Play"/></button>
<button id="Soundoff"><img src="SoundsOff.jpg" alt="SoundOFF"/></button>
<button id="SoundOn"><img src="SoundsOn.jpg" alt="SoundON"/></button>

Game Conditions:

  • Use Arrows to Move Snake.
  • And exit Game when snake eat itself.It’s your decision you can exit your game if it hits the Wall.

Now Play around with Jquery:

First thing Logic of the Game.It is simple.

  • Create an Array of Snake.
  • Write a function to paint snake array in Canvas.
  • Write a function for creating food.
  • Moving of snake:Remove Tail of the snake(Last element in array) and append to the Head(First Element)
  • Increment the Head.
  • Trigger the Paint function continuously.
  • And write exit conditions.
function paint()
		YourScore="Your Score is: "+score;
		Context.fillStyle = "black";
		Context.fillRect(0, 0, w, h);
		Context.strokeStyle = "black";
		Context.strokeRect(0, 0, w, h);
	  	var HeadX = SnakeArray[0].x;
		var HeadY = SnakeArray[0].y;
		if(direction == "right") HeadX++;
		else if(direction == "left") HeadX--;
		else if(direction == "up") HeadY--;
		else if(direction == "down") HeadY++;
		if(HeadX == -1 ) //If Snake hits Wall then resetting the head position  
		{                //We can write exit conditon here instead of resetting the position.
		}else if (HeadX==w/cw)
		if(HeadY == -1)
		else if (HeadY == h/cw)

		if(Ouroboros_Check(HeadX, HeadY, SnakeArray))
		  alert("Game Over- Your Score : "+score);
		if(HeadX == apple.x && HeadY == apple.y)
			var tail = {x: HeadX, y: HeadY};

			var tail = SnakeArray.pop();
			tail.x = HeadX; tail.y = HeadY;
		for(var i = 0; i < SnakeArray.length; i++)
			var c = SnakeArray[i];
			Draw_pixel(c.x, c.y);
		Draw_pixel(apple.x, apple.y);		


Key Board Movements:

Here is the code for key board movements. This function calls when keydown event occurs.Here I am checking one condition “allowPressKeys” this will disable the arrows when game is in pause mode.

	if (!allowPressKeys){
        return null;
		var key = e.which;
		case 37:
		if(direction!="right") direction="left";
		case 38:
		if(direction!="down") direction="up";
		case 39:
		if(direction!="left") direction="right";
		case 40:
		if(direction!="up") direction="down";


Creating Food and snake:

Creating food is nothing but painting one random pixel within the canvas.Each time generate one random pixel,paint it.For Snake Declare one array.Assign some length initially.Call Paint_cell function.

function Paint_Snake()
		var length = 3; 
		SnakeArray = [];
		for(var i = length-1; i>=0; i--)
			SnakeArray.push({x: i, y:0});

	function create_apple()
		apple = {
			x: Math.round(Math.random()*(w-cw)/cw), 
			y: Math.round(Math.random()*(h-cw)/cw), 

	function Draw_pixel(x, y)
		Context.fillStyle = "white";
		Context.fillRect(x*cw, y*cw, cw, cw);
		Context.strokeStyle = "white";
		Context.strokeRect(x*cw, y*cw, cw, cw);


Checking Exit Conditions:

If snake head meets it’s body then the game will end. Ouroboros_Check take arguments HeadX,HeadY,And SnakeArray,checks whether head meets Snake Body.(The Ouroboros is a symbol representing a Dragan eating own it’s tail.).When game ends we will call Startgame function.

function Ouroboros_Check(x, y, array)
		for(var i = 0; i < array.length; i++)
			if(array[i].x == x && array[i].y == y)
			 return true;
		return false;


Play and Pause Game:

The key of the Game is calling Paint function continuously.  setInterval is a standard Java Script function,we can call it with a function(or code snippet) to execute it for every period in milliseconds.

For Example  var AlertMsg=setInterval(function (){alert(“Hello”);},2000);

The above Code  display alert message for every 2 seconds. And For stopping we use clearInterval(AlertMsg) function.

In play method we will call setInterval with Paint() and in Pause we will call clearInterval.

function play()
	    if(typeof Game_Interval != "undefined") clearInterval(Game_Interval);
		Game_Interval = setInterval(paint, Speed);	
		allowPressKeys = true;

	function pause()
		allowPressKeys = false;


Game Sounds And Buttons:

With <audio> tag in HTML5 We can include sounds in Web page.I am used three audio tags for Gameplaying(background music),GameOver(When snake eat itself) and SnakeEatingFood.






And I included some text between <audio> and <canvas> tags.

<canvas>OOps.. Upgrade your browser</canvas>
<audio>Your browser does not support HTML5 audio.</audio>

If a browser supports canvas and audio tags then it simply ignore the text between the tags.And If not then the browser ignore the tags and displays the text between tags.No need to check canvas and audio support explicitly.


Click here to Play Game now.Turn On Your Speakers,Use Arrows to Move Snake,Use buttons for play pause and sound OFF ON.

If you have any doubts,suggestion feel Free to Post comments.

Download Source Code

Wait before leaving. why can’t you follow me on twitter or be a friend on Facebook or googlePlus or linkedn to get in touch me. or join our mailing list

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Arunkumar Gudelli

I am “One among a million” Software engineers of India.
I write beautiful markup.I make the Web useful.
You can connect me via @twitter or @facebook or Google+ or e-mail.


Lets have chat