Transformations

Translate

When building complex layouts it can get tricky calculating all those angles and offsets. p5js offers so called transformations. Those transforms can modify the underlying coordinate system and where things are draw. Lets start with translate(x, y). When using the translate() command, the origin (0,0) of our coordinate system is moved.

translate(x:number, y:number, z*:number);
point(0, 0); // position 0, 0
translate(100, 100);
point(0, 0); // position 100, 100

Multiple Transforms

Transforms are applied from top to bottom, and multiplied on top of each other:

point(0, 0); // position 0, 0
translate(100, 100);
point(0, 0); // position 100, 100
translate(100, 100);
point(0, 0); // position 200, 200

To better keep track, you can save the current transform push() and if you are done, return to the last saved state pop():

point(0, 0); // position 0, 0
push();
translate(100, 100);
point(0, 0); // position 100, 100
translate(100, 100);
point(0, 0); // position 200, 200
pop();
point(0, 0); // position 0, 0

push/pop do not only restore the transformations, the same goes for drawing styles (e.g. color). push/pop can also be nested.

Besides offsetting the coordinate origin translate(), we can also scale(zoomFactor) and rotate(rad). The center of the transformation is always the coordinate system origin (0, 0).

Example: Polar coordinates

This is for example useful when we are using the polar coordinate system, but we don't want to calculate the offset all the time:

/lectures/2d/transformations/polartranslate/sketch.jsView on GitHub

Rotation

rotate(angle:number);
rotate(Math.PI / 180 * 45); // take angleMode into acount

Scale

scale(scale-factor:number);
scale(2); // 200%

Task: Loops & Translate

Try using offset and rotate in a loop to explore new possibilities for patterns.

Inspiration: Patterns

/lectures/2d/transformations/fractals/sketch.jsView on GitHub

Back to top