HTML5 : Some more details about Canvas

I think by now we are moving good on Canvas element and now its time to know some more basics about the canvas element which will get us up and running on the canvas.

Firstly the co-ordinate system. Well, the origin of the canvas element is at the top-left corner. The x-axis increases its value form left to right from the origin. The y-axis increases its value from top to bottom form the origin.

Now there is an important concept about Canvas element which can get in our way. That is the resetting of the Canvas element altogether. Resetting means, Canvas comes back to its initial stage, the default settings with which it has been created. And this happens when we set either width or height of the Canvas through our code. Well, we can use that to our advantage also. Suppose we have already drawn a lot of drawing on the Canvas and now we want to clear everything. Then we can just set the width and height of the canvas to its original width and height. Though that does not change the size of the Canvas itself, but it will reset the Canvas to its default state removing all the drawings. Lets say that again, even if we set the width and height of the Canvas element to its own width and height, it will reset the Canvas to its default. This can be an advantageous to us if we use it and at the same time it can be a disadvantageous to us if we overlook the effect.

HTML5 : Canvas, an introduction.

Getting started with the canvas on HTML5 is kind of diving right into the HTML5 world and forgetting anything of past of a web browser. I am not going to talk more about it here, rather I think by this time you already have known this. Instead we will jump into the canvas example right away.
Here is the source code of the files for you to download and run.
The HTML code looks as



	


		
		
		
	
	
		
Hello World.

We have added two canvas tags in our HTML document. These canvas tags are kind of actual Canvas of or a drawing board. Yes, now we have a proper drawing board in HTML. I have added two canvas tags so as to know that there is no restriction on the number of Canvas tags. Now lets look at the javascript code. It looks like

$.ready()
{
	//first canvas
	//var canvas_one=$('#board_one')[0];
	var canvas_one=document.getElementById('board_one');
	var context_one=canvas_one.getContext("2d");
	context_one.fillStyle = "#f00";
	context_one.fillRect(50, 25, 150, 100);
	//second canvas
	var canvas_two=$('#board_two')[0];
	var context_two=canvas_two.getContext("2d");
	context_two.fillStyle = "#0f0";
	context_two.fillRect(10, 10, 200, 50);
	//
	context_two.beginPath();
	context_two.arc(300,100,50,0,rads(360),false);
	context_two.closePath();
	//
	// Define some graphics attributes and draw the curves
	context_two.fillStyle = "#aaa";  // Gray fills
	context_two.strokeStyle = "blue"; // Stroke lines in blue
	context_two.lineWidth = 5;       // 5-pixel black (by default) lines
	context_two.fill();              // Fill the curves
	context_two.stroke();            // Stroke their outlines
	
	//experiement with first canvas
	context_one.strokeStyle = "blue"; // Stroke lines in blue
	context_one.fillStyle = "#aaa";
	context_one.fillRect(300, 50, 50, 100);
	//
	// A utility function to convert from degrees to radians
	function rads(x) { return Math.PI*x/180; }  
};

Just open up the HTML file in any web browser to see the drawings in action. And thats simple, is not it! Now we have two rectangles in first canvas and two shapes(one rectangle and a circle) in second canvas.
The important part here is to understand the drawing board or the Canvas in HTML. Well, the thing is first we get the canvas element in our javascript code.

var canvas_one=document.getElementById('board_one');

Now this is not the plane or not the slate where we are going to draw. To get the surface to draw, we have to get that with the code below

var context_one=canvas_one.getContext("2d");

This is known as context and can be a 3d context to draw 3d or 2d context to draw 2d. We are getting the 2d context object here known as CanvasRenderingContext2D object. The 3d context object is referred as “webgl” instead of “2d” in the “getContext()” method. WebGL is an API which is a javascript implementation of OpenGL. Yet, WebGL is a large and complicated API and it is suggested to use a third party library for the same. But all in all we got the idea.

To summarize it all,

  1. Add a canvas tag specifying width and height
  2. Get the canvas element in javascript
  3. Get the context forma the canvas
  4. Start drawing
  5. Enjoy :)

Hope that helps someone one out there.

Some open web libraries

Google Chrome Frame, Enable open web technologies in Internet Explorer.

General Purpose
jquery
mootools
Modernizr
prototypejs

HTML Canvas
processingjs
easeljs
gury
MooTools Canvas Library
pixastic

3D
three.js
C3DL
copperlicht
j3d

Animation on Canvas
cakejs

Vector drawing on Canvas
Paper.js
Raphaƫl

Charts
rgraph

Javascript Graphics library
JSGL
unveil : Data driven application framework

Media
popcornjs
jsfx

Game
craftyjs
gameQuery
xc.js
mibbu
LimeJS
Cocos2D
akihabara
FlixelJS
GameJs
Gamma

Mathematics
Sylvester

Tutorials, examples and references :
creativejs
diveintohtml5
Chrome Experiments
html5games
HTML5 based Game Engines
Js Game Engines

Html, javascript, Css. Where to start?!

This came to me, in the beginning. The confusion is to which one to pick first. It’s kind of chicken-egg problem.
Actually all these are interrelated and very dependent on each other, at least in the beginning.
If you are beginning, learn one of these three and keep moving and concentrating on only one for sometime. After a time, come back and start another. Now, that way worked for me and hope that works.
If you are reffering code, then also try and concentrate on one. Once you are fine with one, move to another one and concentrate on that one for the time you get comfortable on that one, then come back to code and refer the same codebase for the one you are concentrating now.
Hope that works and helps you get started with these technology.

Posted from WordPress for Android through my “HTC Wildfire”.

jQuery : Referring to an element in HTML page

While last post was about referring to an element in through only javascript. Here we will see how to access the same element with the popular javascript library, jQuery.
This is a tutorial straight from the jQuery site itself.
Lets start from the beginning as to add this library to our page. The code will look something like below, depending upon where you have placed your jQuery.js file.


Now lets see the old code of ours when we are doing an alert at the document load complete. The HTML file will look as



  


    
    
   
    
  
  
    Hello World
Hello, this is first div.

Now the point here is to see that we removed the following from the HTML,


That means, HTML code will be pure content. There would be no functional elements inside HTML document. This helps maintain the documents for everyone. Now the code to do the same alert on document load will look as

 $(document).ready(function(){
   // Your code here
   alert("Page is loaded");
 });

Thats simple, but to keep in mind that jQuery gives a “$” to us. Everything we do with jQuery will start with a “$”. Though there are methods to override this, but basic will be using a “$”. And now the whole file will look as



  


    
    
   
    
  
  
    Hello World
Hello, this is first div.

Next, jQuery allows a short hand of the same thing (action on document loading) and we can write that as below

$(function() {
 // Handler for .ready() called.
 alert("Page is loaded");
});

The reference to this is on the jQuery website itself. Now lets see how we can access an element in the HTML document, and jQuery makes it simple as

$("#firstDiv")

The above code is to select our first div on the HTML page.
And for the classes, jQuery allows us to do as below

$(".myClass")

This later thing will select all the elements which are given a CSS class named “.myClass”
These kind of things are called CSS Selectors of jQuery. Now you can understand the codes we have written before, which include a “$”.
Hope that helps someone.

Referring to an element in HTML page

How to select an element in an HTML page? This is often get in my way, while beginning to learn Javascript, CSS and HTML. The simple answer is with javascript we have a method named “getElementById()” and always works as

document.getElementById('element ID');

Lets dive into code and see how things work. Lets say we have an HTML page as



	


		
		
		
	
	
		
Hello World.
Hello you, this is JS.

There are two “div” tags in it and they are having id values as “one” and “two” respectively. Then we have two buttons inside the second “div”. These buttons are having id values as “btnOne” and “btnTwo”. Why we are adding id values?! Well, these are basics of how to access items from inside a page. Its kind of naming a new born in family :) Lets move on and see how we are accessing these elements.
Our javascript file looks as below

var onPageLoad = function ()
{
	 alert("Page is loaded");
	 var myBtnOne = document.getElementById('btnOne');
	 var myBtnTwo = document.getElementById('btnTwo');
	 //alert(myBtnOne+' : '+myBtnTwo);
	 
	 myBtnOne.onclick=function(){
	 	alert ('one');
	 };
	 
	 myBtnTwo.onclick=function(){
	 	alert ('two');
	 };
	 
};

Before going into the javascript, lets see our HTML code again. There is something, we did not look previously. Its

	

What this does ?!! To be very basic, it actually calls a javascript function named “onPageLoad()” , when all the elements on the HTMl page is loaded. That means, we can add any interactivity after the page is loaded. For, if we try to add interactivity before all elements of the page is loaded, then there is a chance javascript engine will ignore those commands which will result in wrong behavior of the page. Therefore its recommended to add functionality to a page after confirming that everything in the page is loaded and this code is exactly doing the same.
Coming to out javascript file, we have to written everything in our “onPageLoad()” function. So the first thing is taken care of, now lets move on and see what else we are doing. Upon page loaded it will “alert” a message to the user saying we are ready to start adding interactivity. Now our main ambition here is to upon clicking those two buttons, we have to alert different messages to the user. We select those button elements with the code

document.getElementById('btnOne');

Next, we have to store these values so as to refer them in our code. We do this by assigning them to a variable as

var myBtnOne = document.getElementById('btnOne');

For the second button we have to do the same thing and the code looks

 var myBtnOne = document.getElementById('btnOne');
 var myBtnTwo = document.getElementById('btnTwo');

Now we know how to access elements from an HTML page. The process is add an id value to the element in HTML page and access them with “document.getElementById(elementName)”. Thats all.
Next we are simply going to add the interactivity. Those are done with

 myBtnOne.onclick=function(){
	 	alert ('one');
	 };
myBtnTwo.onclick=function(){
	 	alert ('two');
	 };

Thats simple, but then there are libraries which make our job even simpler. JQuery is such a library, but that is for a future post.
All the sourceCode can be downloaded from here for your reference.

Hope that helps some one. I would like to listen back from you about the post, leave a comment for suggestions, mistakes or simply thanks.

javascript : Inheritence by prototype

Once we got the basic information and know how, of the “prototype” property of a constructor object, we need some code to test it. So here is another all in one page test for the “prototype” property.
We have 3 constructors and then the prototype property of the constructors are defined as another object. Basically, if 3 constructors namely A,B,C are present, prototype of A is defined as an object created by “new B()”, prototype of B is defined as an object created by “new C()”. There are 4 different properties in all the objects. But the relationship is now as below

A.prototype is new B(); 
B.prototype is new C()
//so the relation is as below
A -> B -> C

That means, “prototype” allows us to make a relation between the objects. We will see that in a moment. Now all the properties of all the objects can be accessed through the object created by “new A()”.
If you have not yet opened the all in one page test for this example, open it now. And click the buttons to see the properties accessed from one Object.

var ClassA=(function(){
	//------define-------
	var a,b,c,d,getA,getB,getC,getD,numberToBeAdded;
	//------configure------
	a='Property a';
	b=500;
	c='Property c';
	d='Property d';
	//numberToBeAdded=100;//prototype object can not access this property, instead the local property will be used
	this.numberToBeAdded=100;//With the use of "this" now its exposed to be accesed from its prototype object
	//------expose-------
	this.getA=function(){
		return a;
	}
	this.getB=function(){
		return b;
	}
	this.getC=function(){
		return c;
	}
	this.getD=function(){
		return d;
	}
	//
	/*
	this.getSum=function(userNumber){
		return userNumber+numberToBeAdded;
	}
	*/
});
//
var ClassB=(function(){
	//------define-------
	var e,f,g,h,getE,getF,getG,getH;
	//------configure------
	e='Property e';
	f=9;
	g='Property g';
	h='Property h';
	//numberToBeAdded=200;
	//------expose-------
	this.getE=function(){
		return e;
	}
	this.getF=function(){
		return f;
	}
	this.getG=function(){
		return g;
	}
	this.getH=function(){
		return h;
	}
	//
	/*
	this.getSum=function(userNumber){
		return userNumber+numberToBeAdded;
	}
	*/
});
//
var ClassC=(function(){
	//------define-------
	var i,j,k,l,getI,getJ,getK,getL,getSum,numberToBeAdded;
	//------configure------
	i='Property i';
	j=300;
	k='Property k';
	l='Property l';
	numberToBeAdded=300;//"this" exposes this number to be overriden by the object which will prototype ClassC(or this class)
	//------expose-------
	this.getI=function(){
		return i;
	}
	this.getJ=function(){
		return j;
	}
	this.getK=function(){
		return k;
	}
	this.getL=function(){
		return l;
	}
	//
	this.getSum=function(userNumber){
		//return userNumber+numberToBeAdded;
		return userNumber+this.numberToBeAdded;//using "this" will override the local property and use the property of the object which would be using this object as a prototype
	}
});

The code to use the prototype is defined as

//makes the object
var objC=new ClassC();
//makes the prototype magic
ClassB.prototype=objC;
ClassB.constructor=ClassB;
//makes the object
var objB=new ClassB();
//objB.constructor.prototype=objC;
//makes the prototype magic
ClassA.prototype=objB;
ClassA.constructor=ClassA;
var objA=new ClassA();

So how it works?!! This magic is simply possible by “prototype”. For example, if we are trying to access one property in an object created by “new A()” and the property is not present in the Object, then javascript engine will look for the property in the “prototype” object of “new A()” and that in our case is an object created by “new B()” and if the property is not found in it, it will search in the prototype property object defined for this object, that is in our case is an object created by “new C()”.

The code below shows, how we are accessing properties from the prototype object through the single object.

//calling own method
objA.getA();
//calling B's method
objA.getE();
//calling C's method
objA.getJ();

If you go through the code here, you must see that there is the use of the key word “this”. This is simply kind of saying that this property is accessible from outside. In Java or Actionscript kind of languages, its known as “public” variables. Remember that, whatever variables need to be exposed to outside, must be defined with the keyword “this”. Going through the code again will show you that, some properties are just defined with “var”, while some other are defined with “this”. Remember, “this” always points to the current object.

Now with these knowledge, we can very well override or reassign values to our objects, which are defined in the prototype object. That means, if some properties are defined in our “prototype” object and they are exposed or public variables, then we can again define the same variables in our Object and our object variables will be used for calculations. This is very interesting and sometimes get some time to understand too. Again, coming back to code, we have a function in our “prototype” object which adds some numeric value to another given number. Both the actual object and “prototype” object have got the value, which needs to be added. But if the prototype value is exposed with “this” then only the value inside function, which calls this variable with “this” will take actual value from the object not the value from the prototype! Thats because, “this” always refers to the current object.

Here is the source code for this example.

Hope that helps someone. Would love to listen comments, suggestions and insights, as I am still learning it.

javascript : prototype

Moving on with my study of javascript, the next thing is “prototype”. Before that, lets say it three times, “Everything in javascript is an Object“.

There are only 3 primitive datatypes in javascript! Though some refer as, there are 5 types, but all in all those are the only ones. These primitive data types are

string
numeric
boolean
//The other two are
null
undefined

Apart from these basic datatypes, everything else is an Object. Though there are predefined Objects in javascript with these primitive datatype names such as String,Number,Boolean,Null,Undefined respectively. Please refer this for a detailed understanding.
Well, the point here is everything is an Object in Javascript. Unlike other programming languages where a Class is needed to create an Object, Javascript comes with Objects from the beginning. The dynamic nature of the language allows us to do so many things in so many ways that there really needs an eye who can see the details, of how things are done.
We know from past tutorial that “prototype” is a property of an Object created with “new” keyword. What does this do? Well, this allows us to link Objects internally!! Lets take a pause and understand another very important lesson of javascript and object oriented programming in general.
In a Class based language(Java or Actionscript) it is thought as, “how to relate the Classes, so that something is possible?”, where in a dynamic language such as javascript, it is thought as “how to relate the Objects, so that something is possible?” Read it for a number of times so that you will get a hang of the metaphor and thought process difference, in mind.
So the point here is the same, we have to relate the Objects itself but not the Classes(Anyway, we do not have classes here in javascript but can fake them though).
Coming back to our “prototype”, its the property of an Object created through the use of “new”. This “prototype” property is also an Object in itself. To test this, let us refer our previous post, and the all in one page test. Go down to the “Understanding Javascript class.” box and click on the “what is prototype” button. The pop-up will say, its an Object. That’s good, lets move on and click on “prototype test” button, now it alerts “undefined” that means, “prototype” is an object but not yet defined! So lets define a prototype and call the same method again. First to assign an object to the “prototype” property click on “initiate with custom prototype” button. That will assign a custom object as the “prototype” property. Now click on the “prototype test” button again, and this time it will alert with some value, other than “undefined”.
Whoa!! Its that simple. Yes it is that simple and for the same reason many confuse with the concept. After all the world has become complicated to understand simple things :) :)

The source code of the example is here to download.
Happy coding.

javascript : Constructor

The confusion between a “function” and a “constructor” is always there. They may seem very similar from outside, but its the implementation that defines the difference. Actually its not even the function definition which is confusing, but its the concept and dynamism of the language itself.
First important thing to remember is everything in Javascript is an Object.
So anything that is Object can be functional. Now there are two ways we can create objects in javascript.
The basic and most used is the object literal with curly braces as

var myObj={
a:12,
b:"another string",
c:function(){}
};

Now if we want to access any thing of this object, the calls will go as below

myObj.a;
myObj.c();

That was quite straight forward for we are accessing an “object itself”.
Now lets see how we can create objects in another way.

var AnObject=function(){
this.a='A String value';
this.b=12345;
this.c=function(){};
this.d='Another String';
};

The above code is kind of a Class, that means it is not a class by any formal definition, but it is kind of a thing which makes objects. If one tries to access anything from it directly as

AnObject.a;
AnObject.c();

It will simply not work!! Why?! For its not an Object yet. To make an object out of it, we have to use “new” and then call it with a “()” like

var anO=new AnObject();
//now call the properties and methods as below
anO.a;
anO.c();

Thats simply because when we call this kind of object, or create objects in this kind with a “new” and a “()”, its called constructor.

varv anO=new AnObject();

Now this function call with a “new” is known as a constructor.
Apart from this difference there is a huge difference in terms of using “prototype” object of the constructor. The “prototype” itself is a huge topic, so its not explained here. The important thing here is to remember that any object which is created with a constructor has a “prototype” property but the objects, which are created with any other methods do not possess the “prototype” object.

javascript : An all in one test page :)

This took me some time to put a decent page online, where one can refer to some very basic concepts of Javascript. Now the page can be accessed here and the source code can be downloaded from this link.

I will go on putting the details of my learning in the coming posts, but for the time being if one needs to play around the codes, please download and start researching.

Keep in mind that every language has its own way of doing things and the more ignorant you become (at least pretend to become) about other languages while picking up one, the faster you will master the one you are studying.

The example and source files convey, how to make and use your own javascript library, how to make a reusable Object in javascript (i am not saying to make a Class here, but a reusable Object, there is a very big difference in those two), how to make a basic CSS3 usage of rounded corners, multiple shadows, custom fonts and text shadows.

Happy learning.