Tuesday, December 21, 2010

Drawing Basic Shapes with HTML5 Canvas (Part 1)

The new HTML standard, called HTML5, has gained so much attention right now. It is supposed to be one of the tools to create cross-platform web applications, the so-called Flash-less / plugin-less. Check out these games on this website http://html5games.com. They are all created using HTML5, JavaScript and CSS. No Flash at all and no third-party plugin needed :) Very nice right?! I was impressed by the variety of games that can be created using HTML5.

Anyway, in this tutorial, we'll learn to how to draw basic shapes using one of the new tags in HTML5, the Canvas tag. Basic shapes include rectangle, triangle and circle.
However, before drawing anything, we must learn about the coordinate system that HTML5 Canvas uses.

What is a coordinate system?

A coordinate system is a map. Each point on that map has values associated with it. Those values are used to identify the point and where the point is on the map relative to the map's origin.

HTML5 employs the Cartesian coordinate system. You definitely learned it in high-school math. But I assume you forget about it already, so here is what a Cartesian coordinate system looks like. 

Please notice that this is the 2D version of the system. There is the 3D version too but we don't worry about it now. 

You can see that each point has a pair of values associated with it. These are called the coordinates of the point and usually denoted as (x, y). X is the position of the point according to the horizontal axis and Y is the position of the point according to the vertical axis. And we need both to locate a point.

For example, point (2, 3) has x value of 2 and y value of 3. How do we know that? Draw a perpendicular line from our point to the x-axis and record the value marked on the x-axis. That value is the x coordinate of our point. Do the same thing for the y axis to get the y coordinate. The origin is a special point whose coordinate is (0, 0).

Coordinate System in HTML5 Canvas

Now back to HTML5. It only uses the 4th quadrant of the Cartesian coordinate system. That means that only the shaded / red-bound portion is used: 


The origin locates at the top-left corner of the canvas rectangular area and the top edge is the x-axis while the left edge is the vertical axis:


This is an important concept because to draw a shape in HTML5 Canvas, you must know the points and their coordinates on the Canvas coordinate system. It is like connecting dots to create a picture. Those dots are your points on the coordinate system and your picture is the shape you want to draw.

That's enough for this post. Take your time to understand this concept. In the next part, we'll go straight to coding :)

No comments:

Post a Comment