In this lesson I will show you how to draw a rectangle using the HTML5 canvas. The process builds upon Lesson 1 where we created the canvas.
The process for drawing a rectangle is relatively straightforward but it does help to understand the canvas coordinate system and some simple geometry.
LESSONS IN THE HTML5 CANVAS SERIES
Part 1: How to Create a HTML5 Canvas
…more to come over the next few days.
As you can see from the image above, the origin is placed at the top left hand corner of the canvas. We then use a standard (x, y) coordinate system with the x direction being horizontal and values increasing to the right. The y value is the vertical direction and increases in the down direction. In this example the top left hand corner of the rectangle will be at position (30, 20). The rectangle is 40 pixels in horizontal length and 20 pixels in vertical length.
QUESTION: Can you state the coordinates of each of the vertices (corners) of the rectangle? Answer at the end of the article.
The code for defining a rectangle uses 4 pieces of information (parameters). We need to define the top left position of the rectangle (the x and y ordinates) and then the horizontal length and then the vertical length.
For the example in the image above we would have:
We also need to apply a stroke to the rectangle. If we include the canvas code from Lesson 1 and the required code for drawing the rectangle above we would have:
We could also achieve the same rectangle by using the strokeRect() function as follows:
In the case above there would be no need to use the stroke() function since this is already called within the strokeRect() function.
The stroke properties can be changed including line width and color.
This will produce the following:
The rectangle can be filled using the fillRect() function with parameters the same as the rect() function.
The best thing to do is to play around with the functions and get lots of practise.
ANSWER: As promised, here is the answer to the question from the start of the article:
Top Left = (30, 20)
Top Right = (60, 20)
Bottom Left = (30, 40)
Bottom Right = (60, 40)
Do you wan to learn more? Join one of the courses on Coding.Academy.