First book review : Aptana Studio Beginner's guide

This came to me as a surprise that I have been asked to review a book and write something about it. I started of with excitement as to finish the book as soon as possible and write something about it. So here it goes.
The book : Aptana Studio Beginner’s Guide
A nice book, as it states from its title. Which is unlikely, is its not only for “beginners only”. This is all you need to get started with Aptana studio but in general Eclipse IDE of any kind.
Aptana Studio itself provides a very solid IDE which is both free and opensource. I love this IDE as I do HTML and JS projects with this IDE. The most appealing thing about this IDE is its cross-platform, so one IDE, one experience everywhere. I must say its a must have for anyone who is serious about Javascript development in general.
Now to get the most out of this nice IDE, this companion book is a must have I would say to get you started and to know what can you do with the IDE.
This book starts with very basic things as to menus and workspace and then move on to deeper topics as to configure it to suite your working style. After working with this IDE for such a long time, I found this book reveals a lot more which came as surprise to me. Things like saving your own customised look and preferences, making shortcuts, the command-line interface inside the IDE and lot more are covered in detail, from a beginner’s perspective.

All in all a nice book to have if you want to get used to Aptana IDE in particular or Eclipse IDE in general.

Thanks a lot to Kenny Dias from Packt Publishing, who gave me this opportunity to review this book.

Things to consider for Cordova (phonegap) development

This came to me as a learning from my first Cordova(phonegap) application development.
The first thing one comes across while developing in Phonegap is “the need for a GUI lib” and the first thing to get in a search result is jQuery, its mobile version and the UI lib. There are many other good libs out there, but this one seems quite ok. While one may choose to use a UI lib or build own lib its up to the developer. In my experience its easy to get started with jQueryMobile and its UI, which uses “Theme roller” to theme the UI.
If one is using jQueryMobile then the trick is to try and solve all the UI problems with this lib itself (not hacking the CSS and JS all over the place in the project). That way the performance will be more and pain to solve all the UI problems is less.

One can just start to make one Cordova application without any libraries, but to be productive soon, the minimum required libraries are
1. jQuery
2. jQueryMobile
3. cordova

Now the most important library which might not be required for the project as a project dependency but is a real time saver is
1. UnderscoreJS
After some playing around with the library and from the suggestion from the community I found Lo-Dash library, which is a drop-in replacement for UnderscoreJS with performance enhancements. So I would recommend using
1. Lo-Dash

Now to coding tips, if one knows the “scope” and “this” in javascript, then writing javascript applications are just fun. So prepare yourself with javascript and how it works, so as to make your life easier developing the application.

Target platform and the library support :
The current Cordova lib might not support your required target platform !! Yeah, that is another thing which might take up sometime to know in the beginning. With each release these libraries kind of deprecate support for old platforms, so check that out in the beginning itself.
The same goes for jQuery and jQueryMbile. Check out whether the latest version of the library supports your target platform.

Native Notifications in Cordova is not supported :
Cordova (phonegap) does not support native notifications. It only supports “alerts”,”confirm” (kind of alert only),”beep”(sound) and “vibrate” (device vibration). But then if you expect to do “alert” notification as iOS and Android devices do (like showing the alerts to user when the application is running in background), then Cordova (phonegap) does not help. One has to write native libraries in native languages and call them from javascript through Cordova.

jQuery tips :
Adding an element to a page and displaying it :
jQuery “append()” and “prepend()” does not update the UI (or DOM), so the added elements are not visible by default. we can hack it by dispatching a jQuery event called “create”, the code will look as below

$("#p_4_content").prepend("hello World").trigger( "create" );

That will tell jQuery to render the UI again, resulting in displaying the added item.

Defining EventHandler Scope :
Another nice thing is calling the event handler in required “scope”. The jQuery library provides a handy method for adding event event handlers as

$('#id_btn').on( 'tap', onBtnTapped );

But then it will be scoped to the same scope as where its being written. If you are writing things in an Object, you might want to get the “scope” in the handler(which is “this”), in order to do that, jQuery provides a “third” parameter option, and one can pass the scope in there. The optional parameter is at the middle instead of at the end (as comparing to other object oriented programming convention)!! But then its the way to go. So the modified code will look as below

$('#id_btn').on( 'tap', this, onBtnTapped ); //Look at the middle parameter
//and the handler code looks as below
onBtnTapped :function(event){
    	//just saving the scope, may be we need it in future here
    	var that = event.data; //here event.data=this (which we passed as second param)
    }

That way inside the handler we can get the “scope” as below

var that = event.data;

The second parameter sent while binding the handler to the event, can be got inside the event handler as “event.data”. Since we are just passing “this”, we can get that in the handler as the example shown above.

Writing the EventHandler :
Well, now the trick writing an eventhandler without making the application behave unreasonably is a challenge. It might sound silly but it is not. If you write an event handler as

onBtnTapped: function(event){
    	//Do something
    }

Then its bound to get in your way of the behavior of your application. The jQuery fix is to do a “return false” in all the handlers. But then that might not be the case of your handler as that might return in between the code itself. So the fix is make a call to “preventDefault” as soon as you are inside the handler method. the modified code will look as below

onBtnTapped: function(event){
        event.preventDefault();
    	//Do something
    }

That is the start, I will post more tips as I fight through the scenarios.

BackboneJS : the basics

This is my first javascript framework for application development and this post is supposed to be for anyone who is just beginning with this framework. While I am still learning this framework, the points here should make one comfortable at least to get started in learning the framework itself.
First things first, here is a slide show of a talk I had given to a group regarding BackboneJS. The source code for the same slideshow (which is made with backboneJS itself) is available here.
Well, to start with BackboneJS in itself provides a structure to the web application development. It is heavily dependent on UnderscoreJS and RequireJS. RequireJS allows us to use javascript modules and load script files at one point in a .js file rather than the script tags in an html document. UnderscoreJS provides very nifty utility to ease our javascript development.
BackboneJS is supposed to be a model-view-controller framework and while we can call it like that but the real “C” here stands for “Collection”.
The view class here in BackboneJS is kind of controller. Once got the data, it can make other views or can decide which view to render at what position on the html page. There is a concept called “template” and Underscore gives that facility to us as we are developing in BackboneJS. These templates are kind of placeholders for content and once we got data, we can render html with the help of these templates.
Collection class actually is a glue between frontend and backend as its responsible to get data from server and set data in server.
I would say it a quite straight forward framework, though it takes some time to get used to the behavior of the framework. Who come to javascript frameworks for the first time will take sometime to get used to it. Though the documentation is quite good in the official website, there are things which are not documented, so it will take some time to search and undertand the concept. Overall I would say an elegant framework.
Happy coding

CoffeeScript, the first taste

On my path inside javascript land, I came across CoffeeScript which compiles to JavaScript. One week of handson to the language and I tried to write a simple phonegap application with CoffeeScript taking jQueryMobile into action. The whole project is on github, the whole of the CoffeeScript is here for your reference.

First thing I liked about the language is, it compiles to a very decent, rather I would say the best handwritten JavaScript. That itself is a huge advantage if one wants to learn JavaScript.
The code is modular and compiler is straight forward so its an immediate likable thing if one wants to code ahead in JavaScript. The community is vibrant and the official documentation itself is quite nice.
It is a must try for any javascript developer.

Things to keep in mind, and must be kept in mind while coding in CoffeeScript, are
1. The indentation should be exactly same
2. Each function returns the lastline of code in the function
(I faked it in above code by writing “null” at the end of each function)

Happy Coffee

haXe : First HTML5 circles

We are going to write an application, which will just draw out different color circles to the HTML5 canvas. Once the number of circles reaches 1000, we are going to clean it up and start over again.
There are 2 files, the first one is the program entry point Main.hx and then there is an ApplicationStage.hx. Basically we are not going to write anything in the program entry class, rather we will keep it clean all the time. So for us, the first class to write some code is ApplicationStage.hx. Below is the code for the two files;

class Main 
{

	public static function main() 
	{
		new Main();
	}

	public function new()
	{
		var as:ApplicationStage = new ApplicationStage();
		Lib.current.addChild(as);
	}

}

We are not doing anything on Main class, rather creating an object of ApplicationStage and adding it to the stage. So the code for ApplicationStage looks as below.

package ;
import flash.display.Graphics;
import flash.display.Sprite;
import flash.events.Event;

class ApplicationStage extends Sprite
{
	private var count:Int;
	private var max:Int;

	public function new() 
	{
		super();
		this.init();
	}

	private function init():Void
	{
		this.count = 0;
		this.max = 1000;
		this.addEventListener(Event.ENTER_FRAME, onEachFrame);
	}

	private function onEachFrame(e:Event):Void
	{
		//count
		this.count++;
		//draw
		var g:Graphics = this.graphics;
		g.beginFill(Math.round(Math.random()*(256*256*256)),Math.random());//Math.random() * 256, Math.random()
		//g.beginFill(0xFF0000,1);//Math.random() * 256, Math.random()
		g.drawCircle(Math.random() * 600, Math.random() * 400, Math.random() * 50);
		//g.drawCircle(20,40,10);
		g.endFill();
		//clear everything
		//trace(this.count);
		if (this.count>this.max)
		{
			g.clear();
			this.count = 0;
		}
	}

}

If you are coming from Flash, it should look as if you are writing Actioinscript ! So no worries.
Now the last thing is to write the nmml file for NME. We save it with name compile.nmml and it looks as below.

<pre>
<?xml version="1.0" encoding="utf-8"?>
<project>
 
	<app title="haXe_Day_8" 
		file="haXe_day_8"
		main="Main" 
		package="com.example.saumyaray" 
		version="1.0.0" 
		company="saumya"></app>
		
	<window width="600" height="400" 
			fps="30" 
			orientation="portrait" 
			resizable="false" ></window>
 
	<set name="BUILD_DIR" value="Export" ></set>
 
	<classpath name="src" ></classpath>
	<haxelib name="nme" ></haxelib>
 
	<ndll name="std" ></ndll>
	<ndll name="regexp" ></ndll>
	<ndll name="zlib" ></ndll>
	<ndll name="nme" haxelib="nme" ></ndll>
</project>
</pre>

Finally the command for compiling it to HTML5 will go as below in the commandline.

haxelib run nme test compile.nmml html5

Well, that all to it.
The source files are here for your reference.

haXe : Compiling to javascript

After all these tutorials in pure javascript, lets see is there is any other help from any where for our javascript programming. The best thing to happen is haXe. If you have not heard about it yet, haXe is a language on its own! But why I need to learn another language?! Well, there is not much difference in javascript and haXe. As you have already seen, inside javascript also we have different libraries and we need to learn them to use them, lets look at haXe, for now, as another library (which is obviously not). Now, you will be amazed to know that after you know haXe and start writing on haXe, your code can be compiled to whole lot of different languages including C++,PHP and javascript.
First of all one need to download and install haXe. The installation is quite straight forward and the help at its own website is quite nice. I do not think you will get stuck there, but if it is, please drop me a line here or best is ask in their forum.
The hello world application for javascript I am writing here is straight out of haXe documentation. I am just putting it here for I got stuck at the compiling time and want you to get going in haXe without ever stopping anywhere.
I hope by this time, you have installed haXe on your machine. Lets write our first haxe class.

package ;
class Main 
{
	public static function main() 
	{
		trace('Hello');
	}
}

The purpose is to show a message we passed in “trace” function. We will write an HTML file to use the javascript file compiled from the above haXe code. Now save the above in a file with a name say “Main.hx”. Yep, “.hx” is the native HAXE extension. Suppose we are going to save the generated javascript file inside the “js” folder and with name “my.js”. Lets say that our HTML file is named as “HelloWorld.html”. So the folder structure looks as below.

src
   Main.hx
bin
HelloWorld.js
   js
     my.js

So our “Main.hx” is on “src” folder and all our generated code is inside “bin” folder. The generated javascript is inside “js” folder, which is inside “bin” folder. You may be asking, where are the javascript and html files?! Well, we have decide the structure of our application first and now we will move on and create those files in necessary folder. First lets see the HTML file code, which is as below.

	<div id="haxe:trace"></div>
	<script src="js/my.js"></script>

Basically we need a div element with id “haxe:trace”, so that all our “trace()” function calls in our “.hx” file will be written inside this div . We are ready for action now. All we need is to compile our haXe code to javascript.

Open command prompt (terminal in Mac) and move to the src folder, where we have stored our “.hx” file. Now write the code below in the terminal and press enter.

haxe -main Main.hx -js ../bin/js/my.js

Now go inside “bin/js/” folder and you will be amazed to see our “my.js” file is created there. Open the html file in a browser to see the result of it. The “Hello” we typed in trace is now written to the HTML page div tag. Sweet, is not it!
Suppose we want an real alert, a javascript alert, then modify the haxe code as below.

package ;
class Main 
{
	public static function main() 
	{
		js.Lib.alert('Hello World');
	}
}

Next process, I hope you know already :) . Compile it in HAXE compiler as below to generate the JS file with the modified code. This means fire up the command prompt and put the same command as we did before, which is as below.

  haxe -main Main.hx -js ../bin/js/my.js

Now open the same html file in the browser again to see the alert message.
Yeehaa :) we got a nice javascript code generated from haXe.

Here is the source files with comments in it for you to play with.

Happy haXeing :)

HTML5 : Canvas with mouse interaction.

Here we are going to study about the creation of Canvas dynamically and the basic mouse interactivity with the Canvas elements.

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

We are going to use a separate sprite sheet and try to make the scene a little more interesting than the last one. I would say to download the source files and see the example for yourself to see what is it doing. Basically there is a scene on the background with 6 tables and a girl doing some experiment on third table. Towards the left top corner of the scene, there is another girl trying to do some magic with its magic wand. If you look at the code, the scene with the girl doing experiment is a straight forward drawing from the sprite sheet as we did that in last tutorial. The girl with the magic wand is drawn in a dynamically created Canvas. The code looks as below.

//creating canvas dynamically
canvasGirl=document.createElement('canvas'); 
canvasGirl.width=100; 
canvasGirl.height=100;
//get the context
contextGirl=canvasGirl.getContext('2d');
//customise canvas
canvasGirl.style.background='transparent';
canvasGirl.style.zIndex=5;
//add the canvas to the document
document.body.appendChild(canvasGirl);

The first thing is to create a new canvas with “createElement(‘canvas’)”. That will make a new canvas. Now we have to get the context to draw something on it. This is done with “getContext(’2d’)” as usual, nothing new here. And lastly, we have to add our newly created Canvas to the document and this is done with “document.body.appendChild(canvasGirl);” code. Thats beautiful. Everything else in the code is just configuring the canvas.
Once the canvas and context are available to us, we can do anything we are able to do to a Canvas. So the girl with the magic wand is drawn to the context of this Canvas element. The code looks as below.

resetContext(canvasGirl,contextGirl);
contextGirl.drawImage(photo, 108*counter+10, 900, 96, 64, 0, 0, 96, 64);

First we are resetting the Canvas, so as to draw new content on each timer. Since the girl with magic wand is actually an animation, we call the code above repeatedly on a timer event. And first we clear the context with our own function and then redraw an image from sprite sheet at the same place on the canvas, so as to make an animation. If you are following along with the previous tutorials then the reseting of context code should not be new to you, else the code looks as as below.

resetContext=function(canvasRef,contextRef){
	contextRef.clearRect(0,0,canvasRef.width,canvasRef.height);
};

All we have, are two layers of drawing and animation drawn from the same sprite sheet.
Lets do some mouse interactivity with these elements. The code looks as below.

//------------ adding mouse interaction --------------
$('#board_one').mouseup(function() {
  	alert('Canvas with Tables');
});
$(canvasGirl).mouseup(function() {
  	alert('Canvas with Girl, doing magic.');
});

The trick here is JQuery’s neat job. Just remember anything wrapped with $() will give a JQuery element of the same HTML element. So our dynamically created Canvas is made an JQuery element by

$(canvasGirl)

Notice that there is no ‘#’ before the name as it is before ‘board_one’, thats for the ‘board_one’ we are referring the HTML element with id ‘board_one’, while the other one we are creating dynamically in javascript and converting it to a JQuery equivalent.
Thats nice and if you have not done yet, please go ahead and click on the board to get an alert showing different message and if you click on the girl with magic wand, that will alert a different message.
This is quite simple and straight forward interactivity, but I think you got the point.
Happy coding :)

And yes, I made it to one month of continuous posting, highly influenced by Keith Peters. Though it was not all javascript and I missed some dates, but all in all, the number of posts in a month is achieved. I am quite happy about my effort and a big thanks to all of you, who read it.

HTML5 : animating on a Canvas with sprite sheet

We have already seen how to animate on Canvas in one of our last tutorials. That was quite straight forward as we were using Canvas drawing straight out of the box. Here we will use our newly learnt tools(loading and drawing bitmap image in canvas) to make an animation.
The source files are here for you to download and play.
The concept is the same though as in re-drawing in the canvas at a regular interval, but instead of drawing with drawing API, we will be drawing image.
First of all lets understand what a sprite sheet is? The sprite sheet is an image! Just an image? Yes, its just an image file. In that image file, we should have almost all the images needed for our purpose. That means, one image file consisting of all the images required in a project. Why its necessary? Good question. The reason being we have just one call to the server and all our image data is loaded. The next reason is to update the image data. Suppose we want to update the graphics all at once, we just have to update one image file.
If you are going through the image file in our source, the image file has 12 different images of a character. All we are going to do is, cycle over each character over a time. That we can do with a “setInterval()” javascript function.
Lets see the javascript code first and then we will go learn it.

$.ready()
{
	//------------- 1. defining the variables and functions----------------
	var resetCanvas,resetContext,
		canvas_1,context_1,
		image_data,photo,loadPhoto,imageLoaded,timer,onTimer,counter,animate;
	//------------- 2. configuring ---------------------------------------
	//get the canvas and context
	canvas_1=$('#board_one').get(0);
	context_1=canvas_1.getContext('2d');
	counter=1;
	//---------------functions----------------------------------
	//resetting the width and height, it automatically resets the canvas
	//clear the board, quick and dirty, its a HACK!!
	resetCanvas = function (canvasRef){
		canvasRef.width=canvasRef.width;
		canvasRef.height=canvasRef.height;
	};
	//clear the board
	resetContext=function(canvasRef,contextRef){
		contextRef.clearRect(0,0,canvasRef.width,canvasRef.height);
	};
	
	imageLoaded=function(evt)
	{
		var originalPic=evt.target; 
		animate();
	};
	
	loadPhoto=function(path)
	{
		photo.src=path;
	};
	
	animate=function(){
		timer=setInterval(onTimer,150);
	};
	
	onTimer=function(){
		resetContext(canvas_1,context_1);
		
		//draw again
		if(counter>=12)
		{
			counter=0;
		}
		context_1.drawImage(photo, 97*counter, 0, 97, 95, 230, 110, 97, 95);
		counter++;
		//clearInterval(timer);//incase we need to stop the animation
	};
	
	//----------------3. using-----------------------------
	image_data=context_1.createImageData(canvas_1.width,canvas_1.height);
	photo=new Image();
	photo.onload=imageLoaded;
	loadPhoto('images/walkSheet.png');
};

In the beginning we have just defined the variables, then populating them with the required values and scripts. Lastly we are calling our methods and using these variables.
In the beginning we get our canvas and its context. Intitialised the “counter” to 1 as we have 12 different positions of the image, we will be needing a counter to move to next position. So once these properties are populated, we have created some functions, which we use. Then moving on to the actions, firstly there is an “image_data” object, I have created, but not used. That is just to show we can create an image data object from the canvas, which is used to pixel manipulation. So the first thingon making our animation is making an Image object with

photo=new Image();

Then we have to provide an event handler for its image load event, that is done with the code below.

photo.onload=imageLoaded;

If you remember we have already created the “imageLoaded” function, which looks as below.

imageLoaded=function(evt)
	{
		var originalPic=evt.target; //just for the shake of understanding
		animate();
	};

Here the first the “originalPic” variable is defined just to know that we can get the image from the event object as “event.target” . So all in all this “imageLoaded” function actually initialises our animation by calling “animate()”.

animate=function(){
		timer=setInterval(onTimer,150);
	};

And “animate()” function actually intialises the timer for animation and calls “onTimer” function repeatedly at each 150 milliseconds.

onTimer=function(){
		resetContext(canvas_1,context_1);
		//draw again
		if(counter>=12)
		{
			counter=0;
		}
		context_1.drawImage(photo, 97*counter, 0, 97, 95, 230, 110, 97, 95);
		counter++;
		//clearInterval(timer);
	};

This is the place, where all the action is happening. First we have to clear our canvas, that is being done on the first line of this function. Next we check, whether the “counter” is more than 12, if it is then reset it to 0. Thats for we have just 12 different images. Now the line which actually draws our animation is

context_1.drawImage(photo, 97*counter, 0, 97, 95, 230, 110, 97, 95);

This is actually drawing part of the sprite sheet to a particular are in the canvas. Its like copying a portion from the sprite sheet and pasting it in the Canvas. On the next timer event (ie; after another 150 milliseconds, it will copy another portion and paste it in the same location.) we take another portion from the sprite sheet and paste it in the same area of canvas. Since we are clearing the canvas and re-drawing it over a period of time, it seems as if the character is animating! The time of 150 milliseconds is just a guess, we can lower it to see the jerky animation or higher it to see the character move faster. The other values as 97,95 are the width and height of each image in pixels, so that would be different for different sprite sheets.
The last line increments the counter by one.
Now we have a nice looking animation in our HTML Canvas.

Things to not here is, I struggled for sometime to see this working, for I was providing wrong parameter values (97,95 seemed perfect). So if your animation is not visible, first see if the parameter values are correct. Even one pixel higher than the actual image height or width will make the whole thing invisible. Though lower values work fine.

Happy coding.

HTML5 : Canvas pixels, part II

Now we know we can create and manipulate pixels in the Html5 Canvas. That opens doors to some of cool effects we can make with this tool. Here we will make an image invert its color.
The thing to remember here is, we have to get the image data from the context after our image is drawn. That means instead of

createImageData(width,height)

we have to use

getImageData(intialX,initialY,width,height)

The function for creating this look as below,

filterImage=function()
	{
		// Get the CanvasPixelArray from the given coordinates and dimensions.
		var imgd = context_one.getImageData(0, 0, width, height);
		var pix = imgd.data;
		// Loop over each pixel and invert the color.
		for (var i = 0, n = pix.length; i < n; i += 4) {
		  pix[i  ] = 255 - pix[i  ]; // red
		  pix[i+1] = 255 - pix[i+1]; // green
		  pix[i+2] = 255 - pix[i+2]; // blue
		  // i+3 is alpha (the fourth element)
		}
		// Draw the ImageData at the given (x,y) coordinates.
		context_one.putImageData(imgd, 0, 0);
	}

first of all, we take the image data object from the context. Then like the previous example, we loop over each pixel and subtract the channel values from the maximum value so as to invert the color of each pixel. And finally we have to put them into context for rendering.
I would suggest the same thing here as, please try this in every possible browser. While the same code does not work for me on Chrome, it did work in latest Opera.
The source code is here for you to download and play.
Hope that helps someone.

HTML5 : Canvas pixels

Once we know we can do an image drawing in a canvas, lets see if we can at all make a new image from a blank canvas. The answer is yes. We have absolutely accessible to each pixel values of the context of the Canvas.

Let me say you here, if you are not getting the result in one browser, try other browsers. I had tried a long time with the same code in Chrome without any result! But it worked out in latest version of Opera !! Not sure whats wrong but if you test it in other browsers it will save you a lot of time.

The code for image creation is as below.

createImage=function()
	{
		// Create an ImageData object.
		var imgd = context_one.createImageData(width,height);
		var pix = imgd.data;
		// Loop over each pixel and set a transparent red.
		for (var i = 0; n = pix.length, i < n; i += 4) {
		  pix[i  ] = 255; // red channel
		  pix[i +1] = 0; // green channel
		  pix[i +2] = 0; // blue channel
		  pix[i+3] = 255; // alpha channel
		}
		// Draw the ImageData object at the given (x,y) coordinates.
		context_one.putImageData(imgd, 0,0);
	}

All we have to do is create an image data with a width and height, that is done as

var imgd = context_one.createImageData(width,height);

The above code, I have taken the width as canvas width and height as canvas height.
Now we will access each element of that image data array. Since its just an array the pixel values of each pixel is stored linearly as "red,green,blue,alpha" and so we have to loop over each 4th element and get the values of all the channels of each pixel. Thats exactly what our for loop is doing. Then we are only populating the red channel to its max, since we want a red fill canvas image :) !
Lastly the image data must be put on the context so as to render the pixels. The following code does that.

context_one.putImageData(imgd, 0,0);

Thats a simple pixel manipulation we did now with our canvas element.
The source code is available here for you to download and play.