How to use random and loop in the draw loop in p5.js?

Member

by dana , in category: Javascript , 20 days ago

How to use random and loop in the draw loop in p5.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by deron , 19 days ago

@dana 

In p5.js, you can use the random() function to generate random numbers and the for loop to repeat a block of code a specific number of times in the draw function. Here is an example of how you can use both random() and a for loop in the draw function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);

  // Generate a random number for the number of shapes to draw
  let numShapes = int(random(1, 10));

  // Use a for loop to draw a specific number of shapes
  for (let i = 0; i < numShapes; i++) {
    let x = random(width);
    let y = random(height);
    let size = random(10, 50);
    
    ellipse(x, y, size, size);
  }
}


In this example, the setup function is used to create a canvas with a size of 400x400 pixels. In the draw function, the background color is set to a light gray (220) on each frame. Then, a random number between 1 and 10 is generated using the random() function, which determines how many shapes will be drawn.


A for loop is used to iterate numShapes times, drawing an ellipse at a random position (x and y) with a random size between 10 and 50 pixels. Each iteration of the loop will draw a new random shape on the canvas.


This example demonstrates how you can use the random() function and a for loop together in the draw function in p5.js to create dynamic and random visual effects.