How to create a Snake game in HTML5 - part 1

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata
Created: Maveric (28 Mar 2012)
Last edited: hamishwillee (31 Jul 2012)



In this set of articles, we will create a simple game in the style of "Snake" utilizing the HTML5 canvas. The Snake game has been widely adopted game concept in almost all possible electronic gaming platforms. The object of the game is to steer a “snake” around the game area and try to pick up objects while avoiding collision to the walls or blocking objects. The HTML5 element called canvas, as a tag combines the possibility of interacting directly with the JavaScript to allow almost limtless possibilities. Almost all of the modern mobile and desktop web browsers are HTML5 capable.


Any code/text editor of your choice. A HTML5 capable web browser (e.g. Chrome, Safari, FireFox)


For this game we will create one HTML file, a JavaScript file and a two stylesheet files. These are kept separate for convenience and maintenance purposes.

File 1: index.html File 2: reset.css File 3: master.css File 4: snake.js

You can create empty templates to be ready in your code editor.


This is the main game file. We will include all the necessary code files to be loaded by it. This will be done in the <head> section.

<title>HTML5 Snake Game Example</title>
<link href='/reset.css' rel='stylesheet'>
<link href='/master.css' rel='stylesheet'>
<script src='snake.js' type='text/javascript'></script>

This example expects the source files to be read from the root of the directory, so please do adjust the locations should you want to put the files under subdirectories.

The next step is to define the actual graphical game area, which will require us to initialize the HTML5 canvas, this will take place in the <body> section.

<code java>






This page was last modified on 31 July 2012, at 10:31.
81 page views in the last 30 days.