New concept: random()

Make your art more interesting and varied with a little randomness.

Set up

Open a new sketch in p5.js: https://editor.p5js.org/

🚀 Run this code in the draw() function:

rect(100, 100, random(0, 200), random(0, 200));

👥💬 Discuss

  • What happens? Why?

🚀 Run this code in the draw() function:

print(random(0, 400));

Do you see the values in the debug console? random() is a neat function which gives you a random number. That makes it very useful for adding variety and chaos to our programs. You can either use it without parameters:

random() // This will return a random number between 0 and 1

Or you can use it with a range of possible values:

random(5, 10) // Get a random number between 5 and 10

🤔 Predict and 👥💬 Discuss

What will this code do?

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

function draw() {
  background(220);
  
 
}

🚀 Run the code and 👥💬 Discuss

  • What happened?
  • Were your predictions correct? What was different? Why?

Next up…

Getting started