Interaction Design WikiProgramming

P5js Nested Loops


Things can get even more complex as it's possible to nest loops inside other loops.

function setup()
{
  createCanvas(600,600);      
  strokeWeight(1);    
}
  
function draw()
{
  background(255);    
 
  for(let x = 0; x <= width; x+=30)   // draw a smiley every 30 pixels in the width
  {
    for(let y = 0; y <= height; y+=30) // draw smileys every 30 pixels in the height
    {
        smiley(x,y);        
    }
  }
  
}
  
function keyPressed()
{
  if(key == 's') {
    save("screenShot.jpg");
    print("save the screen to screenShot.jpg");
  }
}
  

function smiley(x, y)
{
  noFill();
  ellipse(x, y, 18, 18);  // head
  
  fill(0);
  ellipse(x - 3,y - 3,2,5);  // left eye
  ellipse(x + 3,y - 3,2,5);  // right eye 
  
  noFill();
  arc(x,y,10,10,radians(20),radians(180-20));  // mouth
}


This example doesn't have a screen output, it generates a PDF-File instead. For that you will need to import a script in index.html which allows us to export a pdf file. https://github.com/zenozeng/p5.js-pdf

In html: <script src="p5-pdf.js"></script>

var pdf;

function setup() {
    createCanvas(600, 200, P2D);
	strokeWeight(1);    // line thickness 
    pdf = createPDF();
    pdf.beginRecord();
}

function draw()
{
  background(255);    
 
  for(let x = 0; x <= width; x+=30)   // draw a smiley every 30 pixels in the width
  {
    for(let y = 0; y <= height; y+=30) // draw smileys every 30 pixels in the height
    {
        smiley(x,y);        
    }
  }
  
}
  
function keyPressed()
{
  if(key == 's') {
    pdf.save();
  }
}
  

function smiley(x, y)
{
  noFill();
  ellipse(x, y, 18, 18);  // head
  
  fill(0);
  ellipse(x - 3,y - 3,2,5);  // left eye
  ellipse(x + 3,y - 3,2,5);  // right eye 
  
  noFill();
  arc(x,y,10,10,radians(20),radians(180-20));  // mouth
}


Exercise

Example Solution

let w = 60;

function setup() {
  createCanvas(660,660);
  noStroke();
  colorMode(HSB);
}

function draw() {
  background(255);
  for  (let i =1; i<=10; i++) {
    for  (let j =1; j<=10; j++) {
      let hue = j* i* 3;
      fill(hue, 150, 255);
      myShape(i*w, j*w); 
    }
  }
}

function myShape(x,y) {
  ellipse(x, y, w, w);
}