Variables

Variables are placeholders for our values. These values can be anything. A number, text, lists, or objects. We will learn about these options later. For now we will stick to numbers. We can write a number with or without a decimal: for example 8 or 8.2.

To declare a variable in JavaScript we use the keyword var. The way we do this is by writing var, and then choose a name for the variable. We can then pass a value to that name using the equal sign = and putting a number after it.

var myNumber = 10

Here we have declared a variable, given it the name myNumber, and assigned it to the number 10. Whenever we use the variable myNumber, JavaScript will replace it with the number 10. Write this line of code outside the setup() and draw() functions. We do this so that we have access to it in both functions. That's how JavaScript works. If we put the line inside the setup() function, we can't access it inside the draw() function. This is the scope of a variable. How far it can reach.

Open the file animate.js inside the 3-animation folder. Here you see that the variable declaration at the top of the file. The variable is then used inside the draw() function. Now the size of rectangle will be 10 pixels in width and height.

var myNumber = 10;

function setup() {
    createCanvas(400, 400);
    background(200);
}

function draw() {
    rect(100, 100, myNumber, myNumber);
}

We still just have a static image. That's because our variable does not change its value. How can we change the value of an variable? We can assign a new value to it. One way we can update our variable, is by assigning the variable to itself plus 1. That way we increment the value by one. Inside the draw() function, after the rect(100, 100, myNumber, myNumber);, write this:

myNumber = myNumber + 1;

Now you should see the box animate. It will get bigger every frame, until it grows outside the canvas. You have just made your first animation. Your animation should look like this:

http://animate1.surge.sh/

Exercise 5:

Instead of animating the size of the rectangle, try animating its position. Click on the link below, and try recreating what you see.

http://animate2.surge.sh/

(Note: another way of increasing a number is by writing this: myNumber += 1. This does the same thing as what we wrote above. We can also increase by any number we want, like for example 10: myNumber += 10. This will add 10 to the myNumber variable, and if you change the + to -, we subtract 10 from our varialbe. Like this: myNumber -= 10).