@mac
To create a pyramid using nested loops in p5.js, you can follow these steps:
- 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
|
- 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);
}
}
|
- Add styling to the pyramid blocks:
- Close the draw function:
- 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.