Creative Code: 9/20

Technical Lessons

Documentation of p5.js functions used in this lesson. Bolded items are essential.

Example programs showing the topics discussed in this lesson:


One variable can be used to control many different kinds of things. In this example sketch, the mouseX variable is used to control the position and size of the circle in several different ways:

A subtle point. Globally-scoped variables are those which are declared outside the draw() and setup() functions, and which can therefore be modified anywhere in the program, and have values that persist across animation frames. (Example: click counter sketch)


The random() function, documented here, produces random numbers within a specified range. For example:

  • var x = random(100); // This generates a random number between 0 and 100, and assigns the variable x to have this value.
  • var y = random(100, 200); // This generates a random number between 100 and 200, and assigns the variable y to have this value.
  • More information is in this Coding Train video about random()
  • Here’s a sketch that produces a random composition whenever the user clicks:


Precise positioning

Using coordinate transformation commands, it is possible to to rotate(), scale() and translate() graphic elements where you want them. Note: You’ll need to use push() and pop() to keep yourself sane!


Helpful Videos