I'm very new to JavaScript and the P5.js library and I'm currently attempting to get my head around nested loops. I'm attempting to iterate both x position and fill transparency and I've got it working using a while loop, however when I attempt to create a nested for loop, I come undone.
Here is the while loop:
function setup() {
createCanvas(500, 200);
}
function draw() {
//background colour
background(0,0,0);
let x = 20;
let alpha = 50;
while (x <= width){
fill(255,255,255,alpha);
rect(x,70,60,60);
alpha = alpha + 50;
x = x + 100;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/p5.js"></script>
And here is my attempt at a for nested loop:
function setup() {
createCanvas(500, 200);
}
function draw() {
//background colour
background(0,0,0);
for (x = 20; x <= width; x = x + 100){
for (alpha = 50; alpha < 255; alpha = alpha + 50){
fill(255,255,255,alpha);
rect(x,70,60,60);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/p5.js"></script>
I've spent 2 hours attempting everything that I can think of to get it working, it's time to get some help.
Would I be correct in assuming that I'm going about this the wrong way, alpha is a P5 function and is obviously causing the console output above? The while loop works, but I am very much attempting to understand how loops work and this will help me a great deal. Thanks for your help.
A nested loop is the wrong approach for this task. You have to use a nested loop when you want to iterate through an 2 dimensional array (for instance a grid), but it is completely useless and superfluous for a 1 dimensional case (like a line or row). In this case you can iterate the control variables in one loop:
function setup() {
createCanvas(500, 200);
}
function draw() {
//background colour
background(0,0,0);
for (let x = 20, alpha = 50; x <= width; x += 100, alpha += 50){
fill(255, 255, 255, alpha);
rect(x, 70, 60, 60);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>
You can use a nested loop to iterates the x and the the y coordinates of rectangles arranged to a grid:
function setup() {
createCanvas(500, 200);
}
function draw() {
//background colour
background(0,0,0);
let alpha = 50;
for (let y = 20; y <= height; y += 100) {
for (let x = 20; x <= width; x += 100) {
fill(255, 255, 255, alpha);
rect(x, y, 60, 60);
alpha += 10;
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>