Dan Hill
Dan Hill

Reputation: 35

p5.js colouring each rectange using array

I have a simple 2x3 grid of rectangles here. I would like to fill each rectangle seperately with specific colours. I'm fairly new and I think this requires an array. It should look something like this image.

var colours =[];

function setup() {
  createCanvas(1000, 700);
}
function draw() {
  background(220);
  
  for (let y = 0; y < 2; y++) {
    for (let x = 0; x < 3; x++) {
      let xpos = x *200;
      let ypos = y *200;
      rect(xpos, ypos, 200, 200);

    }
  }
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>

Upvotes: 2

Views: 1308

Answers (1)

Rabbid76
Rabbid76

Reputation: 211278

Use color to define an array of colors:

let colors = [color(255, 0, 0), color(255, 255, 0), color(0, 0, 255)];

Set the fill color by fill:

fill(colors[x]);

var colours =[];

function setup() {
    createCanvas(1000, 700);
}
function draw() {
    background(220);
    
    let colors = [color(255, 0, 0), color(255, 255, 0), color(0, 0, 255)];
    for (let y = 0; y < 2; y++) {
        for (let x = 0; x < 3; x++) {
            let xpos = x *200;
            let ypos = y *200;
            fill(colors[x]);
            rect(xpos, ypos, 200, 200);
        }
    }
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>

Upvotes: 2

Related Questions