Oct 222012

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.


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

Oct 102012

In my earlier post I explained basic concepts of Local Storage API.If you are new it’s better to refer Understanding Local Storage API in HTML5.

Before writing web pages in html5 you need to think about two things.

  • Browser compatibility:- You can check browser compatibility using html5test.com. Right now Chrome is leading with 437points(out of 500) and next Maxthon,Opera,Safari,Mozilla and finally as you expected IE9 with 137points.IE 10 is under development which supports html5 features up to 319points.
  • What if the browser wont support? some of the browsers wont support new html5 features in that case we need to provide meaningful alternative.
  • And check whether feature is supported by browser or not for web storage you can use window[“localstorage”]
But the good news is that all the browsers(even the mobile browser you can check all these details in html5test.com) are moving towards the HTML5 standards.And HTML5 is not declared as standard by W3c right now(Expected to be stable standard by 2014) May be w3c will come up with proper solution to support the older browser(it’s depends on how fast users upgrading their browser).


Now I will explain how to use Web Storage API to save user preferences in client browser especially in eCommerce sites.Usually most of the eCommerce sites save user search preferences using cookies.When the user loads page for the next time browser will send cookie along with http request and displays the search preferences.But we can use web storage Api to do the same effectively (without much complexity).


Multi Search using Web Storage API:
This is the Sample HTML file for Multi Search functionality.
  • One text box for entering search items
  • One button for adding search items to local storage as well as DOM
  • One button for clearing local storage and DOM elements
  • And one list for showing search items.



JavaScript Code:-


The following are the main functions in Java Script
  • Adding search items to LocalStorage
  • Adding search items to DOM
  • Getting existing Search Item list from local storage.
  • Deleting search Items.
Adding search Item to Local Storage:-
 Local storage api is all about key/value pairs.Creating unique keys are the main important thing in this Local storage.Here I am using Date function to create unique keys.First I am creating unique items and then I am pushing those items into another array ‘searchItemsArray’.To access items easily.As the Local storage supports only string format Iam using JSON.stringify() to convert array to string and save it into localStorage, and JSON.parse() to parse string to array.


Getting existing search items from localstorage:-
After adding key into localstorage we need to get existing searchItemsArray,If searchItemsArray not existing (i.e., if we are loading page first time) we are creating an array and adding it into local storage else we are getting existing ‘searchItemsArray’


Adding search items to DOM:-
And finally we are reading each element in ‘searchItemsArray’ and adding it into DOM.


Deleting the search Items:-
And I added one button for clear all search Items and also if the user clicks on single element I am clearing that element using onClick method on ‘li’ element.




Oct 062012
Html5 Local Storage

In this Tutorial I will explain all the Basics of HTML5 Local Storage API.

It’s often referred as Web Storage. Web storage is nothing but client side storage.Right now we are using cookies for the purpose of storing objects locally in client machine(in browser).

There is a big debate happening around cookie vs Local Storage I don’t want to get into that but I will start with Cookie basics, limitations of cookies and then Html5 Local Storage

Why Cookie?

Cookies are mainly used in Shopping carts to customize the user experience by storing data locally(user specific).I will explain how cookie works in high level.

  • Your playing a game in online,to maintain your state of game server will store cookies in your browser.
  • If you close the browser and try to access the same website then browser will send cookie along with HTTP request.
  • Based on Cookie,server customize the user experience and retrieve the state of a game
  • And Cookies are Domain Specific i.e., abc.com cannot access cookie of xyz.com.
Cookie is nothing but Key Value pair stored in a browser.

Limitations of Cookies :-

  • Cookies can able to store only 4k of data. For each domain browser will assign 4k of memory.
  • Each time browser has to send cookie along with HTTP request,it’s inefficient especially if you are using mobile device with not a lot of bandwidth
  • Difficult to handle(I mean coding) cookie key value pairs within a HTTP request.
  • Each time we are sending cookie along with http request,Are we sending our personal data?
  • Finally everything is handle at server side,there is no client side development.

Introduction to HTML5 Local Storage:-

In HTML5 there is no concept of Cookies everything can be done by Local Storage API.A simple JavaScript API in the browser for storing Key value pairs that are persistent and you are not limited to 4k of memory.

Html5 Local Storage

Html5 Local Storage

HTML5 Local Storage browser support:

Almost All browsers are supports HTML5 Local storage. I checked the Local storage API browser compatibility  in HTML5test.com Here is the  result   click here.

Internet explorer 6,7 ,Opera 10 ,Firefox 3.0 are not supporting this HTML5 local storage API anyway we are not using these browsers now a days

HTML5 Local Storage limit:

All browsers today offering 5-10 MB of storage in every user’s browser.i.e., For each domain 5MB of local storage.

HTML5 local storage supports different web apps and mobile apps.Local storage is nothing but your app can store data in browser to reduce communication needed with the server.

A page can store one or more key/value pairs in the browser’s local storage.And later use key to retrieve value. These can be done by Local Storage object in local storage API.

You may thing why Local Storage why not Web Storage,Web refers to something more and we are implementing at client side,local make sense instead of Web.

Html5 Local Storage Example:-

Before going to example first we will understand basic functions of html5 local storage. With “localstorage” object we can create a key using ‘setItem‘ method.And to retrieve value use ‘getItem‘ method.


Most of the browsers support local storage object but safer side you can check browser compatibility as shown below


And also keys are unique for example 


Now value contain value2 not value1. And one thing Local Storage stores only string values.But in Shopping cart if we want to store item counts and prices in Local Storage you need to use parsing.


Html5 Local Storage Array:-

Instead of using setItem and getItem methods we can use arrays as shown below


And Local Storage has two interesting things :Length property and Key method.Length property holds number of items in the local store.And get can be used to retrieve value as shown below

for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
var value = localStorage[key];

or you can use foreach loop as shown below

for (var key in localStorage) {
var value = localStorage[key];alert(value); }

And you can remove keys from Local Storage using removeItem method: localStorage.removeItem(key);

Html5 Session Storage:-

If you substitute the global variable sessionStorage everywhere you’ve used localStorage then your items are stored only during the browser session. So, as soon as that session is over (in other words, the user closes the browser window), the items in storage are removed.The sessionStorage object supports exactly the same API as Local Storage.

Where we can see Local Storage keys and Values:-

LocalStorageinChromeAnd we can see the local storage key values in browsers using developer tools as shown in the pic.In developer tools select resources and Local Storage. you can select key and delete from browser itself instead of using local storage removeItem method.

To clear entire local storage you can use


But how to use this clear method you need to create one sample HTML page.No need to bother download this ClearWebStorage.html file and click on clear button it will clear the total localStorage elements.


What happens if 5MB storage exceeds:-

If 5MB storage exceeds browser should throw QUOTA_EXCEEDED_ERR exception.Most of the modern browsers will throw this exception.And remember don’t forgot to use try,catch loops.If you are not using it may crash the browser if it exceeds 5mb storage.Do you want to test this? download this BlowUpStorage.html file and test.

Important things to be remember while using Local Storage API:-

  • There is no naming conventions available for HTML5 LocalStorage keys,but those should be unique.
  • The problem here is,For example you have one domain say abc.com it has two applications or two pages Page1 and Page2 Page1 can access localstorage items set by page2 and vice versa, because those two pages are under the same domain.So you need to select naming scheme for your local storage that won’t conflict with other applications at the same domain.
  • And if you want to store arrays or objects into local storage use JSON.stringify to store the value and JSON.parse to retrive the value.
For naming you can follow a simple procedure for example if you have two apps in your domain,assign one unique appid for each app and then use that appId to create local storage keys as shown below.
Html5 Local storage Naming Convenstions

Html5 Local storage Naming Convenstions

Is HTML5 Local Storage can replace Cookies?

We can do everything with Local Storage api in HTML5 that can be done using cookies,but it cannot be the end of cookies ,because we are using cookies from long back and Most of the websites are still depending upon cookies,

Imagine webpages without cookies?

How many developers willing to change their codes?

This is my personal opinion if you have any concerns feel free to post comments.

And in my next post I will try to explain Local Storage in HTML5 with an example.

I hope you understood the basics of HTML5 Local Storage API in this Tutorial. Now go through the next post to learn how to use Local Storage API HTML5 LocalStorageStorage example.

Thanks for Reading my Post. Please Take a look around My blog,Keep up to date with my Posts..
Wait before leaving. why can’t you follow me on twitter or be a friend on Facebook to get in touch me

And Finally Don’t Forgot to Join Our Reader List.

You might Like

Beginning Html5

A new era in web development

Html5 canvas tutorial

Optimization WordPress Plugins & Solutions by W3 EDGE