How to Draw A Rectangle Using the HTML Canvas
In this brief tutorial we will explore how to draw using the HTML canvas.
STEP 1
The first thing to do is to create a div element to hold your canvas:
Line 8: the canvas has been given an ID of 'myCanvas' and dimensions of 600px width and 400 pixels height.
STEP 2
Next, reference the canvas and set up a 2d space:
Line 11: we reference the element with the id of 'myCanvas'. You can use whatever name you wish as long as you use the corresponding id in your canvas tag (see line 8)
Line 12: this returns a drawing context. In other words, we are creating a 2 dimensional drawing. There are other options available but we will stick with a simple 2d context in this tutorial.
STEP 3
Now let's draw a rectangle:
The best thing to image is that you are holding a pen or pencil and about to draw the rectangle.
Line 13: we begin a new path...a bit like saying "hey, let's get ready to draw a new shape"
Line 14: the first thing we need to do is locate where we are going to start drawing the rectangle. We move the pen to the position on the paper. In this case it is 100 pixels across from the top left corner and 50 pixels down. The top left hand corner of the canvas is the origin (0, 0)
Line 15: we now move the pencil to the point 300, 50. At this stage a line has not been drawn. Imagine that your pen is using invisible ink. You have laid down an invidible marker which will be drawn over later (line 18)
Lines 16 and 17: we now mark out the second and third lines.
Line 18: we now close the path. This is the equivalent of marking out the last line. Since we started a path on line 12, the browser is aware of where we need to go to close that path.
Line 19: now that the full path of the rectangle has been marked out we now 'ink' the rectangle by stroking the path.
You should now have a rectangle drawn on the canvas.
STEP 4
If we wanted to adjust the style of the line then we can use the following commands:
Line 18: we set a line width of 4 pixels
Line 19: we set the line style to be coloured red
We now have a rectangle drawn with a red line of width 4 pixels.