random

random() is a p5.js function which returns a random number from the specified arguments.

We can use it to achieve many things, sush as: positioning our elements in random position, move the elements randomly, create shapes of random size etc.

It can take 0,1 or 2 arguments.

If 0 arguments are defined, it returns a number between [0,1).

If 1 argument is specified, it returns a number between [0, number).

If 2 arguments have been specified, it returns a number between [numer1,number2).

Example 

Here is an example code which creates ellipses in random positions and with random size: 

//create variable for ellipse size
let size;

function setup() {
  createCanvas(800, 600);
  background(75);
}

function draw() {
  // the size of the ellipses will be between (20,200]
  let size = random(20, 200);
  // all of x ,y and size of the ellipse will be random
  // the x position will be between (size,(width-size)] so that the ellipse will always be within canvas
  // the y position of the ellipse will also be always inside the canvas
  ellipse(random(size, (width-size)), random(size, (height-size)), size);
}

You can see the result of the above code here

Exercise

  1. Open your Visual Studio editor and the p5yourName folder.
  2. Open the file ex812.js in your editor and save it as ex925.js
  3. Open the file ex812.html in your editor and save it as ex925.html
  4. In the ex925.html file, update the link to ex925.js  from exersice812.js
  5. Go to the index.html file and create, under Module 9, a link to the ex925.html  file with the title "random".

Modify the ex925.jsfile and use as a base the above example to make the ellipses taking random colors. You can see here an example.

Answer:

//create variable for ellipse size
let size;

function setup() {
  createCanvas(800, 600);
}

function draw() {
  background(67,34,89);
  // the size of the ellipses will be between (20,200]
  let size = random(20, 200);
  // create random fill for the ellipses
  fill(random(1, 256),random(1, 256),random(1, 256));
  // all of x ,y and size of the ellipse will be random
  // the x position will be between (size,(width-size)] so that the ellipse will always be within canvas
  // the y position of the ellipse will also be always inside the canvas
  ellipse(random(size, (width-size)), random(size, (height-size)), size);
}

Do a Git commit with the message "random".