In p5, we can change shapes by changing the fill, shape and size, but we can also change their relationship to the coordinate system using transformations.
Usually we draw everything starting at 0,0
in the upper left corner, but we can change that. We can also change the scale, rotation and shear of shapes. And we can do it multiple times throughout the program. This is an convenient way to create new effects and animations.
translate
translate moves the origin to a new point on the canvas.
Notice that each ellipse has the same xy coordinate, 0,0
, but appear in different places.
Also notice that transformations are cumulative, meaning they add together.
rotate
Translate is useful because rotations are done around the origin point, 0,0
. To rotate a shape around a specific point, translate is required.
rotate rotates the canvas around it's origin point.
Be default, angles in p5 are measured in units of PI
. PI is a mathematical constant that describes the relationship of a circles circumference to it's diameter and is equivalent to roughly 3.14. For our purposes, it is only necessary to know that PI
is half a rotation and TWO_PI
or PI * 2
is a full rotation. p5 also has smaller measurement including HALF_PI
and QUARTER_PI
.
Rotation in p5 goes positive in the clockwise direction.
scale
Scale is pretty straight forward, it changes the scale of the shapes.
shear
shear
is a little more complicated. Shear shifts the points of a shape away from a set point. In the example with rectangle, two point of the rectangle are shifted while the other two points stay in place. This creates a visual effect where the shape appear to be bending around a point. Shear is applied with the shearX
or shearY
function.
push & pop
In p5, transformations accumulate as they are added, so if you want to translate multiple shapes from different location, you may need to use multiple transformations.
p5 has two functions that make it possible to do multiple transformations in one sketch: push
and pop
.
push()
saves the current transform (any rotation or translation), and pop()
returns it to the saved state. Usually we want to save the transform at the original state, starting with 0,0
in the upper left, and no rotation.
Animating with transformation
Using transformation functions can add some new effects to our animations.