Submodule 17.2: Advanced p5 functions and transformations
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
- Open your Visual Studio editor and the
p5yourName
folder. - Open the file
ex812.js
in your editor and save it asex925.js
- Open the file
ex812.html
in your editor and save it asex925.html
- In the
ex925.html
file, update the link toex925.js
from exersice812.js - Go to the
index.html
file and create, underModule 9
, alink
to theex925.html
file with the title "random".
Modify the ex925.js
file and use as a base the above example to make the ellipses taking random colors. You can see here an example.
//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".
- See more about the random() function