CSC 240: Computer Graphics

Lab 3: Transformations in Canvas

in-class

In this lab we will explore transformations in HTML Canvas. For this lab, use pair programming with your random partner (i.e. use one person's computer, then email the code to the other person afterward).

Step 0: Study the code

Download lab3.html. At first, there should only be a blue square in the upper left corner of the screen. In the next steps, we will practice translating, rotating, and scaling the square.

Step 1: Translations

Inside draw() (under step 1), call translate twice with two different sets of values. An example is shown below:

graphics.translate(x,y);
graphics.translate(30,40); // translate objects 30 pixels right and 40 pixels down
Make sure to have this code before the code that draws the square. This makes sure that the vertices of the square are multiplied by the translation matrix. Now switch the order of your translate statements. What effect does this have on the shape?

Step 2: Rotations

Comment out the translate code, then call rotation twice with two different angles. I would recommend using very small values, since the angles are in radians.

graphics.rotate(angle);
graphics.rotate(0.1); // rotate objects 0.1 radians (which way?)
What happens? Which way does the shape rotate? Does it make sense? Now switch the order of the rotation statements. What effect does this have on the shape?

Step 3: Translate and Rotate

Comment out the rotation code. Now choose one rotation and one translation. Observe the result. Now switch the order of the statements. What effect does this have on the shape?

Step 4: Translate and Scale

Comment out the code above. Now choose one translation and write one line to scale the shape.

graphics.scale(ax,ay);
graphics.scale(2,3); // scale x by 2 and y by 3
Now switch the order of the statements. What effect does this have on the shape?

Step 5: Animation!

First uncomment out the code that draws the circle (at the top of draw()), and comment out any transformations from the previous steps. Our goal will be to get the square to rotate around this circle in an animation. Right after calling draw(), call rotateCube using a timer:

timer = setInterval(rotateCube, 150)
Run this code. What happens? Does it make sense why? The rotations are accumulating! Now add one line of code in the right place to move the square so it rotates around the circle.

Finish Up

You do not have to turn this lab in, but make sure both you and your pair programming partner have a copy by the end of the lab. Feel free to continue this lab to help answer the questions in Homework 3.