Let’s start to play around with our drawings in a more advanced way.
As we learned in the second chapter, the origin of the canvas is at the top-left, and this is usually also the reference that is used for the scale or the rotate command. If you want to rotate your drawing not around this point, but instead around the center of your emoji, you have to move this point with translate(x, y);
. If we would like to move our Emoji around, we first have to create a new state with push();
, then move the origin with translate(x, y);
, and draw the emoji. Keep in mind that we have just moved the origin, so we have to adapt the x- and y-positions in our code. At the end, we want to remove our temporary transformations for everything we draw afterwards by calling pop();
.
A translation moves the origin of your drawings to another position
Here is some example code where we moved our origin and draw a rectangle from the new origin with x = 200
and y = 200
:
1
2
3
4
5
6
7
push();
translate(200, 200);
fill(255, 255, 0);
rect(-70, -50, 140, 100);
pop();
As you can see, we draw the rectangle now with a negative x and y position because we have changed the origin with the translate
command. If you have drawn your rectangle before at the position rect(130, 150, 140, 100);
with the origin in the top-left corner, you have to subtract the values in the translate command from the x and y position of the rectangle. For example, 130 - 200
for x and 150 - 200
for y to draw the rectangle at the same position.
Here you can see a bit more complicated example with my emoji:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
background(255, 255, 255);
strokeWeight(2);
push();
translate(150, 150);
// The background of the emoji
fill(255, 255, 0);
ellipse(0, 0, 200);
// The eyes of the emoji
fill(255, 255, 255);
ellipse(-30, -20, 40);
ellipse(20, -30, 60);
// The pupils of the emoji
fill(0, 0, 0);
ellipse(-20, -20, 10);
ellipse(0, -40, 10);
// The mouth and the teeth of the emoji
fill(255, 255, 255);
rect(-60, 20, 120, 40, 20);
line(-60, 40, 60, 40);
line(-40, 20, -40, 60);
line(-20, 20, -20, 60);
line(0, 20, 0, 60);
line(20, 20, 20, 60);
line(40, 20, 40, 60);
pop();
To change the position of your emoji, you only need to change the values used as parameters in the translate
command.