Applying Specific Colors to Grid Array

Hi! I’m brand new to coding with P5JS and I need some help. I’m currently taking a class for it and I’ve been watching a bunch of The Coding Train videos. For my specific project I’m trying to implement 30 unique colors into a grid array. From class/watching videos I have learned how to apply random colors to a group of grid squares, but not how to apply a specific color to an individual one. I don’t need help with all of the squares, but if someone can help with a few squares I should hopefully be able to do the rest.

For an example, let’s say I want the color (255, 0, 0) in grid square (2,4), the color (0, 255, 0) in grid square (5,1), and the color (0, 0, 255) in grid square (3,6).

I have the grid set up-

Here’s the section of my code:

var cols = 5;
var rows = 6;

function setup(){
createCanvas(750,1125,WEBGL);
}

function draw(){
background (0);

translate(-width/2,-height/2);
for (var i= 0; i < cols; i++) {
	for (var j = 0; j < rows; j++) {
		var x = i * 150;
		var y = j * 187.5;
		stroke(0)
		fill(255);
		rect(x, y, 150, 187.5);
	}
}

Welcome @NeatCoder47

If you want to specify the colors for each cell in the grid, you could draw it from an array:

var colors = [
  // col 0     col 1      col 2
  ['#FF0000', '#00FF00', '#0000FF'], // row 0
  ['#FFFF00', '#00FFFF', '#FFFFFF']  // row 1
]

function setup(){
  createCanvas(300, 200);
}

function draw(){
  for (var row = 0; row < colors.length; row ++) {
    print(colors[row]); // print a row of color values
  }
}

You can modify the for loop to draw the grid arrangement you’re after.

Hello,

Take a look at this:

https://processing.org/tutorials/pixels/

In the section Pixels, pixels, and more pixels there are some good examples that you can adapt to your project.

There me be something similar in the P5.js resources.

:)

Expanding from @tabreturn in setup you could iterate through a color array and set the colors randomly, or use conditional statements to choose the colors for the required cell, then in draw itterate through all cells and use the corresponding color from the color array.

Array of Colors - Processing 2.x and 3.x Forum