Random and Noise


Let’s add a little bit of uncertainty:

function setup() {
  createCanvas(500, 500);
  frameRate(10);
}

function draw() {
  background(random(255), random(255), random(255));
}

What about creating ellipses in random positions?

Make them appear only in a central square of 300×300! Random can accept a minimum and a maximum value.

random(0, 100);

Add a random fill!

Try to restrict the color range!

Random can be used for triggering events every once in a while:


 var bingo = round(random(1,60));
 print(bingo);
  
  if(bingo == 2)
  {
 	//do something...
  }

Random positioning vs random walk:


function setup() {
  createCanvas (300, 300);
}
 
function draw() {
  background(200);
 
  var rx;
  var ry; 
  rx = width/2;
  ry = height/2;
 
  rx = rx + random(-10, 10);
  ry = ry + random(-10, 10); 
  ellipse(rx, ry, 40, 40);
}

var rx;
var ry; 
 
function setup() {
  createCanvas (300, 300);
  rx = width/2;
  ry = height/2;
}
 
function draw() {
  background(200);
  rx = rx + random(-10, 10);
  ry = ry + random(-10, 10); 
  ellipse(rx, ry, 40, 40);
}

Noise

Perlin noise is an infinite random sequence of values changing harmonically. It is the basis of a lot of special effects and procedural computer graphics and it’s much more interesting than random.

The sequence will appear “natural” if you take contiguous samples (xoff).

var xoff = 0.0;

function draw() {
  background(204);
  xoff = xoff + .01;
  var n = noise(xoff) * width;
  line(n, 0, n, height);
}

Noise example with variable xoff

Posted in