Issues with overwriting

I am trying to have multiple same-size rectangular panels of differing colors appear on the canvas. However, each panel is appearing the same color. Each color is stored in an array declared globally and each element thereof is a hexadecimal string. I have tried multiple solutions, which include wrapping in an IIFE, as well as declaring a second variable within loops, with the same result. What should I do? Code pasted below.
<
let panels=[];

function setup() {

let colors = [’#cca700’,’#1c7eff’,’#8400ff’,’#bfff00’,’#61ff8b’,’#e85d00’,’#02d902’,
#e3c500’,’#fff700’,’#ffd900’];

createCanvas(windowWidth,windowHeight);
loadImage(‘bg2.jpg’, img=>{
imageMode(CENTER);
image(img, width/2,height/2,900,400);
});
background(0);

for(let i=0;i<width;i+=width/10){   
  for(let j=0;j<colors.length;j++){
      (function(){
      panels.push(new Panel(i,colors[j]));  
    })(j);
    
  }
}

}

function draw() {

for(let i=0;i<panels.length;i++){

panels[i].display();  

}

}

class Panel {
constructor(x,col){
this.x=x;
this.col=col;
}

display(){
fill(this.col);
rect(this.x,0,width/10,height);

}
}
/>

Thanks.

You’ve divided your window into 10 sections, but in each section you are adding rectangles of every color! But when you draw all your rectangles, only the last one drawn appears (because it is drawn over all the other rectangles in that section).

The real problem is that you have 2 for loops, when you really only need one. There should only be one rectangle per section, and it should be one color.

You loop should look more like this:

for( let i=0; i<10; i+=1){
  panels.push( new Panel( i * width / 10.0 , colors[i] ) );  
}

untested code, YMMV

1 Like

Thanks. This ended up working.

1 Like