Drawing multiple shapes with loops

In the previous section, we expanded our ability to draw shapes to being able to draw random shapes with random colors. Okay, but now we need to try and see if we can make many random shapes on the screen.

This means we’re going to introduce two new things, that are kind of duals to each other: loops and lists.

Now technically speaking “lists” are actually called “arrays” in JavaScript, but list is a much more evocative term that I think will help make the code make sense.

An empty list is represented as two square brackets with nothing in between, like in the following code snippet:

let xList = [];
let yList = [];
let sList = [];
let cList = [];

This creates three separate lists, ones we’ll use to keep track of the data for all the squares of different shape and color we’re going to make.

Next, we’re going to use a loop in order to generate two hundred shapes. This code snippet will go in the setup function.

for(let i=0; i<200; i++){
    xList.push(random(0,350));
    yList.push(random(0,350));
    sList.push(random(10,50));
    cList.push(color(random(0,255),random(0,255),random(0,255),random(100,255));
} 

This lets us store the data for two hundred different shapes in these lists. The listName.push is a way of putting things into a list one item at a time, so we do this for each of the four lists. You’ll also notice that we’re putting four numbers in the color function this time: the four argument controls how transparent the object is. The bigger the number the more solid, the closer to 0 the more transparent.

Now, the flip side is that we need to be able to get the data back out of these four lists. To do that, our code in the draw function will look like this:

for(let i=0; i<200; i++){
  fill(cList[i]);
  square(xList[i],yList[i],sList[i]);
}

Our final code will thus look like:

let xList = [];
let yList = [];
let sList = [];
let cList = [];

function setup() {
  createCanvas(400, 400);
  
  for(let i=0; i<200; i++){
    xList.push(random(0,350));
    yList.push(random(0,350));
    sList.push(random(10,50));
    cList.push(color(random(0,255),random(0,255),random(0,255),random(100,255)));
  }

}

function draw() {
  background(200,200);
  for(let i=0; i<200; i++){
    fill(cList[i]);
    square(xList[i],yList[i],sList[i]);
  }
}

and when you run this program you’ll get a result like:

That’s already starting to actually look more like a real art project, isn’t it? Try increasing the number of squares made or varying size and color ranges of them to see what else you can do.