I've managed to create 3 'for' loops and assign each set a different color. I then decided to combine the 3 'for' loops into one nested loop to keep it concise, but I can't get the color (stoke of the lines) to change for each section (like I had when the loops were separate). I was wondering if anyone could help me add the color into the 1 nested loop.
I have the 3 separate for
-loops so you can see how it is suppose to look. And I commented out the code that I want to include (the nested loop without the colors) in my final code.
let wallx = 200;
let wally = 200;
function setup() {
createCanvas(1000, 700);
}
function draw() {
background(220);
noLoop();
//This code combines the 3 'for' loops into a nested loop
// for(let i = 0; i <= 3; i++){
// for (let j = 0; j < (wally+1); j += (wally) / 20) {
// strokeWeight(3);
// (line(0*(i+wallx), j, (wallx*i), j));
// }
// }
for (let i = 0; i < (wally+1); i += (wally) / 20) {
stroke(0, 0, 255);
strokeWeight(3);
(line(0, i, (wallx), i));
}
for (let j = 0; j < (wally+1); j += (wally) / 20) {
stroke(255, 0, 0);
strokeWeight(3);
(line(wally, j, (wallx*2), j));
}
for (let k = 0; k < (wally+1); k += (wally) / 20) {
stroke(0, 255, 0);
strokeWeight(3);
(line(wally*2, k, (wallx*3), k));
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>
Add an array of colors
let colors = [color(255, 0, 0), color(255, 255, 0), color(0, 0, 255)];
Set the stroke
color dependent on i
:
stroke(colors[i]);
Fix drawing the line:
line(0*(i+wallx), j, (wallx*i), j);
line(wally*i, j, (wallx*(i+1)), j);
let wallx = 200;
let wally = 200;
function setup() {
createCanvas(1000, 700);
}
function draw() {
background(220);
noLoop();
let colors = [color(255, 0, 0), color(255, 255, 0), color(0, 0, 255)];
for(let i = 0; i <= 3; i++){
for (let j = 0; j < (wally+1); j += (wally) / 20) {
stroke(colors[i]);
strokeWeight(3);
line(wally*i, j, (wallx*(i+1)), j);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>