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.

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.


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.


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.


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.


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.


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.

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.

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