Graphic JavaScript

Back to index


The student could draw squares and rectangles using the method shown in the previous lesson, but JavaScript provides a method dedicated to drawing rectangles to make this task a bit easier for the programmer. Here's how the method is called:
   ctx.rect(20,30,50,50);
This example will draw a square with sides 50 units long with the upper-left corner at (20,30). That is, the upper-left corner will be 20 units to the right of the left side of the canvas area and 30 units down from the top of the applet area.

This next example will create a rectangle 30 units tall and 100 units wide with its upper-left corner at (50,40):

   ctx.rect(50, 40, 100, 30);


EXAMPLE:
Inspect the code for this example. You will notice that in order for a rectangle to actually be drawn on the canvas, a stroke() method call must follow the call to rect(x,y,w,h). Of course, you can always fill a rectangle with a call to fillRect(x,y,w,h) as you've already seen in previous lessons, but to draw a rectangle that is not filled the rect and stroke methods must be used. Keep in mind that each time you change colors you need to use a call to beginPath() or else you wind up redrawing everything in the most recent color.
Your browser does not support the HTML5 canvas tag.


ASSIGNMENT:
The student will recreate an applet which recreates the pattern displayed in the image to the right. It will help a lot to draw this out on paper and figure out appropriate coordinates before attempting to write the code to produce this image.