Simple Animation - Griffith-ICT/1701ICT-Creative-Coding GitHub Wiki

So far we have only generated static graphics, that don't move.

p5.js makes it very simple to create animations. The concepts for animation draw on some of the things we learned when laying out shapes using loops.

p5.js calls the draw() function 60 times per second. This allows us to generate animations. We can draw something different each time the draw() function is called.

There are two ways we can create the animation. If we clear the background at the start of the draw() function then we can see an object moving. If we don't clear the background the new object positions will be drawn over the previous frame, creating a drawn effect.

Drawing

Let's start with an example that doesn't clear the background.

In this example we are going to move a circle across the scene to the right without clearing the background.

You can see the example here.

var x = 50;
function draw() {
  ellipse(x, 100, 50, 50);
  x++;
}

In this example we have created a variable to represent the x co-ordinate of the ellipse. Each time the ellipse is drawn we increment the x co-ordinate by 1 with x++. The draw() function is called 60 times per second, so the ellipse will move 60 pixels per second.

Because we don't clear the background, we see all of the previous ellipses. We can increase how far the ellipse moves per draw(). Instead of incrementing by 1, we can increment by 5, using x = x + 5, which makes the ellipse move faster.

Moving

We can change our drawing of an ellipse to moving the ellipse by clearing the background for every frame drawn.

var x = 50;
function draw() {
  background(100);
  ellipse(x, 100, 50, 50);
  x = x + 5;
}

Next: Selection