HTML5 : Some more libraries
While going good with at least one post each day, I am not sure what to put next for HTML5 Canvas.
I came across some more libraries for HTML5 Canvas.
KineticJS
Doodle.js
Image Manipulation on Canvas
pixastic
CamanJS
tiffus
JSDrawing
PaintbrushJS
Javascript Code Quality tool
JSLint
Javascript programming
Backbone
Underscore
Knockout
Sugar
We are going good with HTML5 Canvas, I hope there is nothing much left for the basic concepts except one or two, which we will be covering soon. Leave a comment if you feel any tutorial in particular to be included.
Stay tuned and thanks for being here.
HTML5 : multiple Canvas
The interesting thing about Canvas is we can have more than one Canvas and even we can create Canvas dynamically through javascript. Why would we need more than one Canvas !?! There may be many answers to this, but the most important of all is, I think, when we need to update the Canvas. If you remember we have made an animation in our previous tutorial. And diving a little inside of that code will show you that we are redrawing it on each timer event.
The whole idea of animating in Canvas revolves around updating the Canvas on each timer event. But we also know that once something is written/drawn in Canvas
we can not have a reference to it. So in the other hand we have to re-write or re-draw everything again. And this redrawing over and again will take us to a performance problem. Re-drawing the whole canvas with all the elements, again and again is not a good idea and we must avoid it if we can. The best thing to do is to separate elements to different Canvases. And we will never update the Canvas which contains the elements we do not need to be changed. Then only refresh the Canvases whose content needs updating upon timer event. Seems like a plan ? I have done this with the example source code, for your reference.
The source code of the example, contains two canvases and I am updating only the second Canvas as it needs updating.
Point to note here is Canvas refresh does not mean only updating the values, but actually it means erase everything from the Canvas and re-draw everything with the updated value.
Hope that helps to understand the power of Canvas a little better.
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.
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.