GruntJS for CSS minification

With GruntJS, as we saw in the last post, we can minify javascript files, the next in line is the CSS files.
I have updated the Github repo for using CSS along with Javascript files.
The basic setup is not different from javascript setup. Here we have to use

grunt-contrib-cssmin

The confusing part is, for minification we have a lot of options in NPM, and one of them is

grunt-contrib-mincss

So at first I was confused and it did not work for me. Seems like “mincss” is old and have not been updated for a long time. So I am with “cssmin” and that just works.
As usual, install cssmin locally, with

npm install grunt-contrib-cssmin

A note is, if you have “package.json” and “Gruntfile.js” file in the same location, take those files somewhere else while installing new packages from NPM, else it throws some errors. Once installation is complete, bring those files back and that should work as it was before.

Happy grunting.

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.

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.

HTML5 : Text on canvas

Moving on next in our Canvas study, lets see how to draw some text in canvas. The code looks as

context.font = "italic 30px serif";
context.lineWidth   = 4;
textContent="Hello world.";
context.strokeText(textContent, 40, 240);
context.fillText(textContent, 40, 240);

The code should be familiar to you now. First we define the font style, size and type. Then there are as usual two kinds of methods to text, either stroke or fill. First the font type and size is defined. Then line width is defined and finally we stroke the text content with

context.strokeText(textContent, 40, 240);

If the content needs to be filled without the outline, we use fill method as

context.fillText(textContent, 40, 240);

The first parameter is the content to be written. The second and third parameter is the start x and start y of the content.

Thats all to draw the content on the HTML5 Canvas.

HTML5 : Canvas and Context , code and hack! clear and reset.

In one of our previous tutorials, we have seen how Canvas element is reset. And we also know that its a hack but we can use that to our advantage so as to clear the whole drawing, which was previously drawn through code.
Now, lets see the actual API, which is available to us to clear the whole Context of the Canvas element. The code looks as below.

context.clearRect(topLeftX,topLeftY,width,height);

This actually gives us the ability to clear a rectangular part of the Context of the Canvas. For the whole context to be cleared, just pass on the Canvas width and height as below.

contextRef.clearRect(0,0,canvasRef.width,canvasRef.height);

That simply clears of the drawings from the context. The thing is its the context that is being cleared.
Now lets revisit the hack. the quick hack to clear everything from the Canvas. This is done by setting either height or width of the Canvas element itself. Even if its the same width and same height, but it resets the whole canvas, clears everything form it. So this hack works on Canvas element but the actual code to clear, works on the context of that canvas. The hack code looks as

canvasRef.width=canvasRef.width;
canvasRef.height=canvasRef.height;

If you look at the source code, you can find I have written two different functions to call, one using the actual API and one using the hack. The codes are here for the reference.

//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;
	};

Now the clear context function is as below.

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

Just to enforce the idea one more time, the clear function works on the Context object of the Canvas, while the reset hack works on the Canvas element itself.

Hope that clears the concept.

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.