HTML5 : animating in Canvas

It may seem exciting to read the title as to get some animation right away in HTML5 Canvas. But the thing is, there is no direct API for animation. So the point is animation is done through the timer API of javascript. There are two different APIs for timing.

function onTimeout() { 
alert("time is over");
}; 
var timeout = setTimeout(onTimeout, 3000);

The code above will call the “onTimeout” function after “3000″ milliseconds. But the thing is this is only called once.
Now we have another API, which give us the ability to call a function at a regular interval and its called as below

onTimer=function(){
  //code here will be called at a regular interval of 100 milliseconds
};
var timer=setInterval(onTimer,100);

Now, if you look at the source files and the resulting HTML file, there is an animation of a bar going animating from left to right. This is done with the code below.

onTimer=function(){
		context_one.beginPath();//creates a new drawing
		context_one.moveTo(xpos, ypos);
		context_one.lineTo(xpos+1, ypos);
		//define the pen
		context_one.strokeStyle = "#0F0";
		context_one.lineWidth   = 50;
		//make the lines visible
		context_one.stroke();
		xpos+=1;
		//
		if(xpos>=canvas_one.width)
		{
			clearInterval(timer);
			alert ("Animation complete.");
		}
	};

And then calling the function as

var timer=setInterval(onTimer,100);

The function will be called on every 100 milliseconds. We can smaller the interval to smoothen the animation.

Thats simple, is not it! Happy animating :)

HTML5 : Drawing shapes in Canvas

I hope by now we have learned how to draw lines in HTML5 Canvas element. The very next thing is to draw some shapes.
To draw the rectangle the code looks like

context.strokeRect(leftTopX, leftTopY, rightButtomX, rightButtomY);

The above code will create a rectangle with only the outlines. If we want to fill the rectangle with color then the code will look as below.

context.fillRect(leftTopX, leftTopY, rightButtomX, rightButtomY);

In similar way to draw a circle we will use the command to draw an arc as below.

context.arc(x, y, radius, startAngle, endAngle, is_it_anticlockwise);
//example
context.arc(230, 90, 50, 0, Math.PI*2, false);

Now the concept is same as drawing a stroked circle or a filled as to call the stroke method or fill method.

context.beginPath(); // Start the path 
context.arc(230, 90, 50, 0, Math.PI*2, false); // Draw a circle 
context.closePath(); // Close the path 
//define style
context_one.fillStyle = "#F0F";
context_one.strokeStyle = "#FF0";
context_one.lineWidth   = 10;
//fill and stroke
context.fill(); // Fill the path
context.stroke();//stroke the path

The source files for this example is here for you to download and play with it.

HTML5 : Drawing lines on Canvas

Lets start drawing some lines in the Canvas. The point here is, it may feel like we are drawing in Bitmap, but actually its a vector drawing while its being drawn. But then once drawing is complete, it can not be modified directly. The Canvas does not remember any reference to the drawings we have already drawn. So the point to remember is its one time vector drawing. If at all we need to modify it, we have to redraw everything or may save everything inside our code.
The drawing is all javascript. The drawing itself is kind of two part process. First part is to draw the lines. The second part is making them visible. That means the first part draws in memory but not visible. Its only visible after we call the required methods to make them visible.
Lets dive into the code, yay.

canvas_one=document.getElementById('board_one');
context_one=canvas_one.getContext("2d");

We got the context. Now the drawing code comprises of

moveTo(xPosition,yPosition);
lineTo(xPosition,yPosition);

The first command ie; moveTo(xPos,yPos), takes the pen to the “xPos,yPos” position. The next command lineTo(xPos,yPos), draws a line from the pen position to the new position specified by “lineTo”. Thats all, the more number of these commands are called, the points get connected by a straight line. Till now we are only drawing but the are not visible yet.
Lets make the lines visible. These are done by

//define the pen
context_one.strokeStyle = "#000";
context_one.lineWidth   = 5;
//make the lines visible
context_one.stroke();

Thats beautiful. Now are lines are visible. All is well and good, but how to create new kind of lines, means how to create lines with different colour and thickness? This is simply done with

//beginPath() creates a new line
context_one.beginPath();

After this all we are going to do is moveTo and lineTo commands to draw and the stroke with a different pen.

The source files are here for you to download and test.

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.

Javascript : some things to keep an eye on Canvas

This came to me as a surprise, when we were doing the last tutorial. If you see the code in detail, we have the code below.


The above code is not on the head section of the HTML document! Rather it came after everything in the HTML document. I hope its for the Canvas does not get initialised before the code is executed. But moving the script to the last section of HTML document, it worked just fine.
I hope someone have got better explanation about the effect, but thought its better to share as this very thing took me a while to get it working. After all I am also learning now and sharing my experience at the same time.
The next thing to keep an eye is the code below on javascript

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

The above code is pure javascript without utilising jQuery library. But the same thing can be achieved by the code below

var canvas_one=$('#board_one')[0];

The thing which went wrong for me in the beginning is that I was doing

var canvas_one=$('#board_one');

First I was hoping this should work, but it did not unless I access the zeroth element. Hopefully this also can be explained by some experienced developer, but then as we are going ahead in our learning its better to know how to get the element using jQuery library and its by accessing the zeroth element as below.

var canvas_one=$('#board_one')[0];

Hope that helps someone.

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”.

CSS : getting into it

While going ahead with javascript and all its goodness, we come across terms, which certainly make us curious like id and class. Apart from this we must know the things which we are going to use over and again as a web designer. When we already know about html,javascript and CSS makes up the whole web page, this is time to know some basics about CSS.
In CSS, we generally define some rules for our html content. Say, we have some structural data with a title and some content. Now this kind of data can be more than one in one page. So we will write some design rules, which our page content can refer to design itself. This kind of rules are called Class in CSS and generally defined with a . (dot) in the beginning.

.topic_title{}
.topic_body{}

The important thing to remember here is these elements will come more than once in a page. Now, there are elements in a page, which occur only once. These kind of elements are referenced as id and defined with a #.

#page_title{}
#page_navigation_menu{}

These are the basic types in CSS and we have already seen how these are referred in javascript too. To add the class styles and id styles in html document we write something as below.

We can even join two different styles together as

 

Now you can imagine how easy or complicated one can make a site design without even touching the content itself.
Well, there are some default elements in HTML as body, h1,p etc. These elements are directly designed with there name in CSS as

body{}
h1{}
p{}

How cool! Now for some global level elements or in general we have an option to define global style for all elements in a HTML page with a * as

*{}

That will assign, the designs described, to all the elements in the html page. This is, kind of, defining the base design of the page and its elements and then individual elements will override their design settings from there own id or class.

Point to keep in mind is, the design which is nearer to the element will override other design rules. That means, if there is a global style and an id or class style is defined for the element, the id or class style will override the design settings of the global style and the element will be visible as its defined in its id or class style.

Hope that helps someone.
If you want, take a reference of the design of our last all in one page here and can download load the source files here and see the basic CSS for the page.

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.