How to use nested loops for a p5.js pyramid?

Member

by mac , in category: Javascript , 3 months ago

How to use nested loops for a p5.js pyramid?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by deron , 3 months ago

@mac 

To create a pyramid using nested loops in p5.js, you can follow these steps:

  1. Set up your canvas and variables:
1
2
3
4
5
6
7
8
9
function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  let rows = 5; // number of rows of the pyramid
  let spacing = 20; // spacing between each block
  let blockSize = 40; // size of each block


  1. Use nested loops to draw the pyramid:
1
2
3
4
5
6
7
  for (let i = 0; i < rows; i++) {
    for (let j = 0; j <= i; j++) {
      let x = width/2 - (blockSize/2) * (i+1) + j * blockSize;
      let y = height - (rows-i) * blockSize - i * spacing;
      rect(x, y, blockSize, blockSize);
    }
  }


  1. Add styling to the pyramid blocks:
1
2
  fill(0);
  noStroke();


  1. Close the draw function:
1
}


  1. Run the sketch in your browser to see the pyramid being drawn.


This code will create a simple pyramid made up of blocks with decreasing width as you move up the pyramid. Feel free to customize the variables (such as number of rows, spacing, and block size) to create different pyramid shapes.