Thursday, July 7, 2011

[HTML5] Canvas -Paint Your Imaginations

Hi Friends,

If we forget about the IE older versions, HTML 5 is doing great job. Though there are so many things that it offers but Canvas is what attracts me. This post might act as introduction to canvas and writing your first canvas.

1. Canvas is nothing special but one HTML5 tag just like div, p, table etc. We use it like 
<canvas height="300" id="myCanvas" width="500"></canvas>

2. Actually just adding this canvas has no use at all. Javascript is one which helps us drawing things on it but even before drawing we need some initialization.
var canvas = document.getElementById("myCanvas");
var c = canvas.getContext("2d");

We just got context from the canvas. This is 2d context using which we can draw line, circles, shapes actually anything that you can think of in 2 dimentions.

3. Now when we have context available, we can start drawing. Lets draw a line first. Assume that you have a pen and paper, now what you will do to draw a line. See the comments above each code line.. isn't that right?
// Choose a point from where you want to start. So lets go to some point(x,y).
c.moveTo(x,y);
// which point you want to go now. Lets say point(x1,y1)
c.lineTo(x1,y1);
Easy so far, huh? But wait, we have to paint it, for that we have stroke(). By default stroke will paint with black color, which we can change using strokeStyle.
c.strokeStyle = "#ff9933";
c.stroke();
Now we are done. If you were not just reading this but writing the same in any html file, there might be a line appearing on the browser :)

4. To draw an arc use
c.arc(x, y, radius, startAngle, endAngle, anticlockwise);
x, y radius are just numbers but angles are in Radians so be careful. Anticlockwise is the boolean value to specify which side to move from start angle. One example Try running this and you will know more.
c.arc(50, 50, 10, Math.PI*1, Math.PI*1.9, false);
Now see, a circle is an arc with angle 0 and Math.PI*2. Just try it.

5. Well there is more to draw but lets close this for today. In my first MSpaint class in 10th standard, we were also given this much info only. If you are curious enough to learn more like me.. go to this link otherwise wait for my next post..

Cheers!!!
Ravi Kumar Gupta

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.