INTRODUCTION TO HTML5 CANVAS
HTML5 Canvas allows
us to draw
various shapes and images and much more including animations in a web page that can be manipulated with JavaScript. This is
actually a bitmapped area so it is very different from Flash and SVG i.e. it redraws the whole screen on every
frame as per the JavaScript calls. This
gives the programmer a very good low level - control over what’s being
displayed.
The html 5 API is very easy and fun to learn even for a newbie. The <canvas> tag is used to create a html 5 canvas. This element have an API supporting client side scripts for drawings. This element have properties width and height which can be manipulated(see the screenshot below).
Here you can see we gave an id to this element. This id ‘can’ will be going to used in our script. Now let’s add an script tag. If you don’t know JavaScript basics then see my JavaScript tutorials(Don’t worry you still be able understand what’s going on).
Write following lines into it.
The first line declares a variable named as
screen(You may give any name to it) and selects our canvas element with its
‘can’, this means now the variable screen represents the canvas element. In the next line we get a
context(a JS object including all the methods and properties for drawing ) for
our canvas and we pass the string “2d” which allows us toDraw 2d dimensional object. There is another context
nowadays for 3d drawings or scenes and is supported by most of the modern
browser but we are for now just going to talk about the 2d only.
If you now open this page in browser you won’t be able to see anything but just a blank page, this is because we haven’t did any drawing stuff yet. So lets draw a rectangle on our canvas. This can be done as shown in the screenshot below.
We have a black rectangle drawn. So what happened actually was that we called the fillRect() method from the context we earlier defined and passed the co-ordinates and dimensions of the rectangle we wanted to draw as shown in the above screenshot .
It can also draw other shapes like arcs and line too. lines can be drawn as shown in the screenshot below,
We can change color of these shapes using fillStyle and strokeStyle methods. If you paid attention to the above code the you will find that stroke() method there. This is used to stroke lines or shapes ,for fill them with some thing we need to do something similar to what we did when drawing the rectangle i.e. use fill instead of stroke. Try writing strokeRect instead of fill if you have any confusion.
Back to the point,for changing color do this,
This is it for now about html canvas, but we are going to
talk about it in detail in next post.
Have nice day!!!
Comments
Post a Comment