Skip to content
On this page

Random

Random is the most important functions of generative arts, it is what will randomize your outputs and make each art unique.

random() follows uniform distribution, which means that all outcomes are equally likely.

When random() is used to generate numbers, all numbers in the output range are equally likely to be returned.
When random() is used to select elements from an array, all elements are equally likely to be chosen.

Art Editor

In this tutorial we will use the https://editor.p5js.org

It's a free online p5js editor that will work to render almost every code you can make.

Preview

random()

By default, random() produces different results each time a sketch runs.

The version of random() with no parameters returns a random number from 0 up to but not including 1.

js
console.log(random()) // output: 0.9791080069516924

The version of random() with one parameter works one of two ways.

  • Number

If the argument passed is a number, random() returns a random number from 0 up to but not including the number. For example, calling random(5) returns values between 0 and 5.

  • Array

If the argument passed is an array, random() returns a random element from that array. For example, calling random(['🦁', '🐯', '🐻']) returns either a lion, tiger, or bear emoji.

js
console.log(random(5)) // output: 4.055644622800395
console.log(random(['🦁', '🐯', '🐻'])) // output: 🐯

Lets draw draw a ellipse of random size in a random position. For this we need to define random values for x, y, width and height

js
let ellipseColor = "#8a2be2"

function setup() {
  createCanvas(500, 500)
  background(200);
  noStroke()

  let x = random(width)
  let y = random(height)
  let circleSize = random(50, 150)
  
  fill(ellipseColor)
  ellipse(x, y, circleSize, circleSize)
}

In this example, every time you run the sketch, the random() function calculates new x and y values, placing the circle in a new position within the canvas.

Preview

Expanding the Concept

You can take this concept further by incorporating randomness into other aspects of your sketch, such as color, size, and even the number of elements drawn. Here's an example that randomly changes the number of circles, their sizes, positions, and colors each time you run the sketch.

js
let ellipseColor = "#8a2be2"

function setup() {
  createCanvas(500, 500)
  background(200);
  noStroke()
  
  let numberOfCircles = round(random(15, 30))

  for (let i = 0; i < numberOfCircles; i++) {
    let x = random(width)
    let y = random(height)
    let circleSize = random(20, 100)
    
    fill(ellipseColor)
    ellipse(x, y, circleSize, circleSize)
  }
}
Preview

Released under the WTF License.