Translate

Specifies an amount to displace objects within the display window. The x parameter specifies left/right translation, the y parameter specifies up/down translation.

Transformations are cumulative and apply to everything that happens after and subsequent calls to the function accumulates the effect. For example, calling translate (50, 0) and then translate (20, 0) is the same as translate (70, 0). If translate() is called within 1, the transformation is reset when the loop begins again. This function can be further controlled by using push() and pop().

Translate in use

If we want to change the origin of drawing, then we need to tell p5.js where to go. Using the translate(x,y) function we can specify an (x,y) location on the canvas. Note: that when doing so, you’ll have to adjust how you draw shapes. In the example below, we start by drawing an ellipse at (0,0) and then translating to the center of the canvas. These coordinates are now the (0,0) for drawing. when we draw another ellipse at (0,0) the ellipse is now at the center of the screen. If we wanted to draw another cirlce back at the old (0,0) we would need to write
ellipse(-width/2,-height/2,40,40)

Video Explanation

Translate and Rotate

Let’s go back to the sketch at the top of the page with the rotating square. If we want to write a sketch that does the same thing we’ll need to set up both a new origin and an angle of rotation.

Video Explanation


Previous section:
Next section: