The translate() function moves the origin from the upper-left corner of the screen to another location. It has two parameters. The first is the x-coordinate offset and the second is the y-coordinate offset:
The translate() function is additive. If translate(10,30) is run twice, all the elements drawn after will display with an x-offset of 20 and a y-offset of 60.
In the previous examples, we saw how transformations accumulate as the program runs. This can become complicated as we will want to return the origin to its original position. This is where a pair of functions called pushMatrix(); and popMatrix(); come in.
The pushMatrix() function records the current state of all transformations so that a program can return to it later. To return to the previous state, use popMatrix().
Rotate works in the same way. Shapes are always rotated around their position relative to the origin (0,0), and positive numbers rotate them in a clockwise direction.
The rotate function requires an angle that detirmines how much the coordinate system is rotated around the origin.
Radians are a different unit of measuring angles as shown in the image below.
180 degrees = PI radians which is about 3.12 multiplied by 2
Rotations accumulate in the same way as translations because you are moving the coordinate system over and over again.
Rotate, translate and scale can be combined in different ways to transform and move shapes.
The order you call transformations affects their position as shown below.
translate(width/2, height/2); rotate(PI/8); rect(-25, -25, 50, 50);
rotate(PI/8); translate(width/2, height/2); rect(-25, -25, 50, 50);
This code produces this result:
As before, pushMatrix() and popMatrix can be used to record the initial translation state and to return to it for combinations of translations.