Get shapes on screen - processing

I have created a grid of thumbs. When a certain thumb is pressed I want the image that is linked to the thumb added on screen. I know i'm supposed to write the loadImages in setup(), but i'm a bit confused on how to do this.
PShape[] Quotes = new PShape[6];
int qLength = Quotes.length;
setup() {
size(1024, 768);
}
draw() {
stroke(bruin);
strokeWeight(5);
fill(wit);
rectMode(CORNER);
rect(guide, 280, bBorder, 145);
noStroke();
fill(bruin);
rect(guide, 280, bBorder, 40);
textFont(kaffeesatzFont);
textSize(30);
fill(wit);
text("Quotes", 80, 308);
createGridQ();
}
void createGridQ(){
xOffset = 30;
yOffset = 325;
xSize = 50;
ySize = 38;
padding = 10;
xPos = padding + xOffset;
yPos = yOffset;
cols = 3;
for(int j = 0; j < qLength; j++){
// Grid
xPos = xOffset + ((j % cols) * (xSize+padding));
yPos = yOffset + ((j / cols) * (ySize+padding));
Quotes[j] = loadShape("Q" + j + ".svg");
shape(Quotes[j], xPos, yPos);
if((mouseX >= xPos) && (mouseX <= xPos+xSize) &&
(mouseY >= yPos) && (mouseY <= yPos+ySize)){
cursor(HAND);
if (mousePressed){
cursor(HAND);
Quotes[j] = loadShape("Q" + j + "groot" + ".svg");
shape(Quotes[j], width/5, height/2-200);
}
}
}
}

You can load an image by declaring a PImage and loading it from a web url or by placing it into your data or source directory (where your .pde files are) and then loading it from there.
PImage img;
img = loadImage("laDefense.jpg");
Processing loadImage Reference
So, replace "laDefense.jpg" with the name of the image you want to use and place that image into your data folder. After that, you can place the image in the scene and manipulate it as you would a shape.

Related

How can you write an algorithm to properly fill a circle using lines from the center?

Currently I try to write code for calculating the parts of the screen you can see and those who can't because of objects that block light in 2d, like in Among Us:
The code should run on a processor with very low specs (at least in 2020), the C64. On such a simple CPU it's not possible to do such complex math fast enough for a game, so I came up with an idea: First of all, I make everything tile based, that makes processing easier and also means that I can just change entire characters or their color cells. Then I just write code for the PC in Processing (that's a coding language similar to Java but easier to use) to calculate how rays of light would move (the following graphic should make that more understandable), first just with a rectangle (and a single quadrant):
Then I wrote some completely messy assembler code for using the recorded coordinates to just keep filling the tiles with an inverted character based on the number of the ray currently being drawn on the ray until they hit an object (/ the tile it wants to fill is not inverted and not a space) and then just go to the next ray. I reduced the radius to 7 so it just takes up 256 bytes, useful for ASM. And that totally worked, I was able to fix every single bug and the result was quite impressive, since I needed to add pause statements or everything ran so fast that you couldn't see anything.
After that worked, I tried it with a circle, setting the points using this code:
int pointNum = ceil(radius * PI * 2); // calculates the circumference
for(int i = 0;i < pointNum;i++){
float angle = map(i, 0, pointNum, 0, PI*2);
setPixel(sin(angle) * radius, cos(angle) * radius);
}
I previously used the Bresenham circle algorithm but that didn't quite work so I tried a more simple way. So ...
All the marked black tiles never get hit by any light, which is a pretty big issue, because it wouldn't make much sense in a game that you just can't see those tiles. The code I used, written in Processing, is:
float[] xPoints = new float[0];
float[] yPoints = new float[0];
float[] xPointsT;
float[] yPointsT;
float[] xPointsHad = new float[0];
float[] yPointsHad = new float[0];
int pos = 0;
float interpolPos = 0;
int radius = 12;
float tileSize = 800.0 / (2*radius+1);
String output = " !byte ";
int pointNum = ceil(radius * PI * 2);
void setup() {
size(800, 800);
frameRate(60);
xPointsT = new float[0];
yPointsT = new float[0];
/*for(int i = 0;i <= radius;i++){
setPixel(radius, i);
setPixel(i, radius);
}*/ //Uncomment this and comment the next 4 lines to get the rectangle version
for(int i = 0;i < pointNum;i++){
float angle = map(i, 0, pointNum, 0, PI*2);
setPixel(sin(angle) * radius, cos(angle) * radius);
}
xPoints = concat(xPoints, xPointsT);
yPoints = concat(yPoints, yPointsT);
}
void draw(){
if(interpolPos > radius){
pos++;
interpolPos = 0;
println(output);
output = " !byte ";
}
float x=0, y=0;
float interpolMul = interpolPos / radius;
x = xPoints[pos] * interpolMul;
y = yPoints[pos] * interpolMul;
interpolPos+=1;//sorta the resolution
background(0);
stroke(255);
for(int i = 0;i < 2*radius+1;i++){
for(int j = 0;j < 2*radius+1;j++){
if((round(x) + radius) == i && (round(y) + radius) == j){
fill(0, 255, 0);
if(output != " !byte ")
output += ", ";
output += i-radius;
output += ", ";
output += j-radius;
xPointsHad = append(xPointsHad, i);
yPointsHad = append(yPointsHad, j);
}
else{
int fillVal = 0;
for(int k = 0; k < xPoints.length;k++){
if(round(xPoints[k])+radius == i && round(yPoints[k])+radius == j){
fillVal += 64;
}
}
fill(0, 0, fillVal);
if(fillVal == 0){
for(int k = 0; k < xPointsHad.length;k++){
if(round(xPointsHad[k]) == i && round(yPointsHad[k]) == j){
fill(128, 0, 0);
}
}
}
}
rect(i * tileSize, j * tileSize, tileSize, tileSize);
}
}
strokeWeight(3);
stroke(0, 255, 255, 64);
for(int i = 0;i < xPoints.length;i++){
line((float(radius)+0.5) * tileSize, (float(radius)+0.5) * tileSize, (float(radius)+0.5+xPoints[i]) * tileSize, (float(radius)+0.5+yPoints[i]) * tileSize);
}
strokeWeight(1);
fill(255, 255, 0);
ellipse((x + radius + 0.5) * tileSize, (y + radius + 0.5) * tileSize, 10, 10);
}
void setPixel(float _x, float _y){
for(int i = 0; i < xPoints.length;i++){
if(_x == xPoints[i] && _y == yPoints[i]){
return;
}
}
for(int i = 0; i < xPointsT.length;i++){
if(_x == xPointsT[i] && _y == yPointsT[i]){
return;
}
}
xPointsT = append(xPointsT, _x);
yPointsT = append(yPointsT, _y);
}
(Instructions to get the rectangle are in the code)
Those mentioned tiles seem to be never hit because the rays on them just jump over them, but what can I do to prevent that? You can decrease interpolPos+=x; to hit more tiles because that way your steps are smaller, but that wastes quite some space, so I don't think that's a good solution. Ideally you could also just decrease the number of coordinates you draw to get a smaller vision. Has anyone a good idea how to do that?
You have chosen wrong method to find all touched cells - instead of point-based way you need cell(squares)-based approach - ray intersects rectangle rather than point.
There is article of Amanatides and Woo "A Fast Voxel Traversal Algorithm for Ray Tracing" for 2D.
Practical implementation.
Example:
Quick-made tracing example. Rays emitted from left top corner go to blue points. If ray meets black cell obstacle, it stops. Pink cells are lighted by rays, grey ones are not.
Okay, I found something that worked for me in my situation: I just used the part that totally works (the rectangle) and then just make that a circle by ignoring every tile hit that's further away from the light source then the radius + 0.5, because without + .5 the circle looks weird. You can try it yourself, here's the code:
float[] xPoints = new float[0];
float[] yPoints = new float[0];
float[] xPointsT;
float[] yPointsT;
float[] xPointsHad = new float[0];
float[] yPointsHad = new float[0];
int pos = 0;
float interpolPos = 0;
int radius = 7;
float tileSize = 800.0 / (2*radius+1);
int pointNum = ceil(radius * PI * 2);
String standardOutput = " !align 15,0\n !byte ";
void setup() {
size(800, 800);
frameRate(60);
xPointsT = new float[0];
yPointsT = new float[0];
for(int i = 0;i <= radius;i++){
setPixel(radius, i);
setPixel(i, radius);
} //Uncomment this and comment the next 4 lines to get the rectangle version
/*for(int i = 0;i < pointNum;i++){
float angle = map(i, 0, pointNum, 0, PI*2);
setPixel(sin(angle) * radius, cos(angle) * radius);
}*/
xPoints = concat(xPoints, xPointsT);
yPoints = concat(yPoints, yPointsT);
xPointsT = new float[0];
yPointsT = new float[0];
}
void draw(){
if(interpolPos > radius){
pos++;
interpolPos = 0;
String output = standardOutput;
for(int i = 0;i < radius + 1;i++){
int indexPos = floor(map(i, 0, radius + 1, 0, xPointsT.length));
output += round(xPointsT[indexPos]);
output += ",";
output += round(yPointsT[indexPos]);
if(i < radius){
output += ", ";
}
}
println(output);
xPointsT = new float[0];
yPointsT = new float[0];
}
float x=0, y=0;
float interpolMul = interpolPos / radius;
x = xPoints[pos] * interpolMul;
y = yPoints[pos] * interpolMul;
interpolPos+=1;//sorta the resolution
background(0);
stroke(255);
for(int i = 0;i < 2*radius+1;i++){
for(int j = 0;j < 2*radius+1;j++){
if((round(x) + radius) == i && (round(y) + radius) == j && sqrt(sq(round(x)) + sq(round(y))) < radius + 0.5){
fill(0, 255, 0);
xPointsT = append(xPointsT, i-radius);
yPointsT = append(yPointsT, j-radius);
xPointsHad = append(xPointsHad, i);
yPointsHad = append(yPointsHad, j);
}
else{
int fillVal = 0;
for(int k = 0; k < xPoints.length;k++){
if(round(xPoints[k])+radius == i && round(yPoints[k])+radius == j){
fillVal += 64;
}
}
fill(0, 0, fillVal);
if(fillVal == 0){
for(int k = 0; k < xPointsHad.length;k++){
if(round(xPointsHad[k]) == i && round(yPointsHad[k]) == j){
fill(128, 0, 0);
}
}
}
}
rect(i * tileSize, j * tileSize, tileSize, tileSize);
}
}
strokeWeight(3);
stroke(0, 255, 255, 64);
for(int i = 0;i < xPoints.length;i++){
line((float(radius)+0.5) * tileSize, (float(radius)+0.5) * tileSize, (float(radius)+0.5+xPoints[i]) * tileSize, (float(radius)+0.5+yPoints[i]) * tileSize);
}
strokeWeight(1);
fill(255, 255, 0);
ellipse((x + radius + 0.5) * tileSize, (y + radius + 0.5) * tileSize, 10, 10);
}
void setPixel(float _x, float _y){
for(int i = 0; i < xPoints.length;i++){
if(_x == xPoints[i] && _y == yPoints[i]){
return;
}
}
for(int i = 0; i < xPointsT.length;i++){
if(_x == xPointsT[i] && _y == yPointsT[i]){
return;
}
}
xPointsT = append(xPointsT, _x);
yPointsT = append(yPointsT, _y);
}
Besides the main difference to ignore tiles that are not in the circle, I also changed that I store the coordinates not in a String but in two arrays, because then I use code to stretch them when there are fewer then radius + 1 points, so I don't have to store multiple circles with different sizes in the C64's RAM, so it meets my main requirements: It should fill every tile and it should be downscalable by ignoring some points at the end of rays. And is if efficient? Uh ... there could be a better solution that fills the circle with fewer rays, but I don't care too much. Still, if you have an idea, it would be nice if you could tell me, but otherwise this question is solved.
Edit: I forgot to add a picture. Don't be confused, I modified the code after posting it so you can also see the blue tiles on the circle.

How do I make a variable randomly equal 1 of 2 numbers? (Processing)

I'm trying for the first time to make Pong. I don't always want the ball to go to the bottom right by adding 3 every single time. How would I make it so it will either do 3, or -3, but no number in between? I know that "||" doesn't work for integers, and "random(-3,3) has the chance of giving me numbers like "0.1" which wouldn't really function in here.
Code:
float circleX = 640/2;
float circleY = 360/2;
float xSpeed = 3;
float ySpeed = 3;
float Color = (255);
float circleHeight = 32;
float circleWidth = 32;
float xAcceleration = -1.0;
float yAcceleration = -1.0;
float paddleColor = 255;
float MyPaddleX = 630;
float OpPaddleX = 10;
float MyPaddleWidth = 10;
float OpPaddleWidth = -10;
void setup() {
size(640, 360);
frameRate(60);
}
void draw() {
background(0);
//Ball
fill(Color);
ellipse(circleX, circleY, circleWidth, circleHeight);
xSpeed = //(WHAT TO PUT HERE?)
circleX = circleX + xSpeed;
circleY = circleY + ySpeed;
//My Paddle
fill(paddleColor);
rect(MyPaddleX,mouseY,MyPaddleWidth,100);
//Bouncing
if (circleX >= OpPaddleX && OpPaddleX + OpPaddleWidth >= circleX) {
xSpeed = xSpeed * xAcceleration;
}
// Top/Bottom Bouncing
if (circleY > height || circleY < 0) {
ySpeed = ySpeed * yAcceleration;
}
//My Paddle Bounceback
if (circleY >= mouseY && circleY <= mouseY + 100) {
if (circleX >= MyPaddleX && circleX <= MyPaddleX + 3)
xSpeed = xSpeed * xAcceleration;
}
//Opponent Paddle
fill(paddleColor);
rect(OpPaddleX,circleY - 50,OpPaddleWidth,100);
//if (circleX < OpPaddleX || circleX > MyPaddleX) {
// circleX = width/2;
// circleY = height/2;
// xSpeed = 0;
// ySpeed = 0;
//}
}
You can generate a number between 0 and 1 and then compare that generated number to 0.5 to "flip a coin" in your code.
Think about it this way: when you call random(1), you'll get a value between 0 and 1. Half of those values will be less than 0.5, the other half will be greater than (or equal to) 0.5.
So you can do something like this:
float x;
if(random(1) < .5){
x = -3;
}
else{
x = 3;
}
You could expand this to choose from more numbers using else if statements, or you could shorten it into a single line of code using the ternary operator:
float x = random(1) < .5 ? 3 : -3;

How to make an (moving) ellipse clickable? Processing

So I started learning processing since a week ago and I'm trying to get a moving ellipse clickable. I followed the processing API, but I can't figure it out. I removed all the code relating to the clickable ellipse because it was a mess.
In the section where I declare all my vars you can see me using:
int breedte = 600;
int hoogte = 600;
These are suppose to be:
int breedte = width;
int hoogte = height;
But for some reason the width and height don't output the width and height declared in:
size(600,600)
So what I'm asking is:
How can I make the (moving) ellipse clickable?
Why I can't use width and height on 'int hoogte' and 'int breedte'?
Thanks in advace.
Main file:
int x = 0;
int leftSide = 0;
int rightSide = width;
int bottomSide = height;
int totalHits = 0;
int totalMiss = 0;
boolean start = false;
int circelSize = 100;
int circelRings = 24;
int circelSpeed = 1;
int circelPositionY = 0;
int breedte = 600;
int hoogte = 600;
String[] buttonText = {"Start","Stop"};
String buttonTextActive = buttonText[0];
int[] buttonColor = {0,90};
int buttonColorActive = buttonColor[0];
int buttonHighlight = 50;
int buttonSize = 80;
int buttonY = breedte - (buttonSize /2);
int buttonX = hoogte / 2 - 40;
void setup() {
size(600, 600);
smooth();
noStroke();
}
void draw() {
if (start) {
circelPositionY = circelPositionY + circelSpeed;
drawCircel(circelPositionY);
if (circelPositionY == (width + circelSize)) {
circelPositionY = 0;
}
}
drawButton();
}
Events file:
void mousePressed() {
// Start or Stop button
if(mouseX > buttonX & mouseX < buttonX + buttonSize & mouseY > buttonY & mouseY < buttonY + (buttonSize / 2)){
if(start) {
start = false;
buttonColorActive = buttonColor[0];
buttonTextActive = buttonText[0];
println("Game stoped");
} else {
start = true;
buttonColorActive = buttonColor[1];
buttonTextActive = buttonText[1];
println("Game started");
}
}
//HERE SHOULD GO THE CLICKABLE ELLPISE
}
Functions file:
void drawCircel(int circelPositionY) {
background(204);
for (int i = 0; i < circelRings; i = i+1) {
int even = i % 2;
if (even == 0) {
fill(255,0,0);
ellipse(-(circelSize / 2) + circelPositionY, height / 2 - (circelSize / 2), circelSize - (i * (circelSize / circelRings)), circelSize - (i * (circelSize / circelRings)));
} else {
fill(255);
ellipse(-(circelSize / 2) + circelPositionY, height / 2 - (circelSize / 2), circelSize - (i * (circelSize / circelRings)), circelSize - (i * (circelSize / circelRings)));
}
}
}
void drawButton() {
fill(buttonColorActive);
rect(buttonX,buttonY, buttonSize, buttonSize / 2);
fill(255);
textAlign(CENTER, CENTER);
text(buttonTextActive, buttonX + (buttonSize / 2),buttonY + (buttonSize / 4));
}
In the future, please try to post a MCVE instead of a bunch of disconnected snippets or your whole project. Also please only ask one question per post.
To make your circle clickable, you're going to have to write code that checks whether the circle is being clicked. That's actually two separate checks. First you have to detect when the mouse is pressed. One way to do that is by defining a mousePressed() function:
void mousePressed(){
// mouse is pressed
}
Then you have to check whether the mouse is currently inside the circle. You can use the dist() function for that: if the distance between the mouse and the center of the circle is less than the radius of the circle, then the mouse is inside the circle. That might look like this:
void mousePressed(){
if(dist(mouseX, mouseY, circleX, circleY) < circleRadius){
// mouse is pressed inside the circle
}
}
Shameless self-promotion: I wrote a tutorial on collision detection in Processing, including point-circle collision, available here.
As for why you can't use width and height at the top of your sketch, that's because code at the top of your sketch is executed before the setup() function fires, and the width and height variables aren't set until after you call size() from the setup() function. So you have to move that code to after you call size().
If you have follow-up questions, please post an updated MCVE in a new question post, and we'll go from there. Good luck.
Processing does not provide an api for hit detection, so you need to implement this by yourself, which I think is a great learning exercise. You can explore the mathematics of an ellipse here.
But the general approach is to use a function like the one below to check that the point you clicked on was indeed inside the ellipse you provided.
boolean InsideEllipse(
float x, float y,
float xc, float yc,
float width, float height
) {
// First half the width and height to get the ellipse parameters
float a = width / 2;
float b = height / 2;
// Now calculate the deltas:
float xd = x - xc;
float yd = y - yd;
// Now the equation of an ellipse is given by
// x^2 / a ^ 2 + y^2 / b ^ 2 = 1
// So if we are inside the ellipse, we would expect the left hand
// side of this expression to be less than one
boolean inside = xd * xd / (a * a) + yd * yd / (b * b) <= 1.0
return inside
}

Processing mirror image over x axis?

I was able to copy the image to the location but not able to mirror it. what am i missing?
PImage img;
float srcY;
float srcX;
int destX;
int destY;
img = loadImage("http://oldpalmgolfclub.com/wp-content/uploads/2012/02/Palm- Beach-State-College2-e1329949470871.jpg");
size(img.width, img.height * 2);
image(img, 0, 0);
image(img, 0, 330);
int num_pixels = img.width * img.height;
int copiedWidth = 319 - 254;
int copiedHeight = 85 - 22;
int startX = (width / 2) - (copiedWidth / 2);
int startY = (height / 2) - (copiedHeight / 2);
How about simply scaling by -1 on the x axis ?
PImage img;
img = loadImage("https://processing.org/img/processing-web.png");
size(img.width, img.height * 2);
image(img,0,0);
scale(-1,1);//flip on X axis
image(img,-img.width,img.height);//draw offset
This can be achieved by manipulating pixels as well, but needs a bit of arithmetic:
PImage img;
img = loadImage("https://processing.org/img/processing-web.png");
size(img.width, img.height * 2);
int t = millis();
PImage flipped = createImage(img.width,img.height,RGB);//create a new image with the same dimensions
for(int i = 0 ; i < flipped.pixels.length; i++){ //loop through each pixel
int srcX = i % flipped.width; //calculate source(original) x position
int dstX = flipped.width-srcX-1; //calculate destination(flipped) x position = (maximum-x-1)
int y = i / flipped.width; //calculate y coordinate
flipped.pixels[y*flipped.width+dstX] = img.pixels[i];//write the destination(x flipped) pixel based on the current pixel
}
//y*width+x is to convert from x,y to pixel array index
flipped.updatePixels()
println("done in " + (millis()-t) + "ms");
image(img,0,0);
image(flipped,0,img.height);
The above can be achieved using get() and set(), but using the pixels[] array is faster. A single for loop is generally faster than using 2 nested for loops to traverse the image with x,y counters:
PImage img;
img = loadImage("https://processing.org/img/processing-web.png");
size(img.width, img.height * 2);
int t = millis();
PImage flipped = createImage(img.width,img.height,RGB);//create a new image with the same dimensions
for(int y = 0; y < img.height; y++){
for(int x = 0; x < img.width; x++){
flipped.set(img.width-x-1,y,img.get(x,y));
}
}
println("done in " + (millis()-t) + "ms");
image(img,0,0);
image(flipped,0,img.height);
You can copy a 1px 'slice'/column in a single for loop and which is faster(but still not as fast as direct pixel manipulation):
PImage img;
img = loadImage("https://processing.org/img/processing-web.png");
size(img.width, img.height * 2);
int t = millis();
PImage flipped = createImage(img.width,img.height,RGB);//create a new image with the same dimensions
for(int x = 0 ; x < flipped.width; x++){ //loop through each columns
flipped.set(flipped.width-x-1,0,img.get(x,0,1,img.height)); //copy a column in reverse x order
}
println("done in " + (millis()-t) + "ms");
image(img,0,0);
image(flipped,0,img.height);
There are other alternatives like accessing the java BufferedImage (although this means the Processing sketch will work in Java Mode mostly) or using a PShader, but these approaches are more complex. It's generally a good idea to keep things simple (especially when getting started).

Fill background with color from array when clicked on rectangle

I've made several rectangles by using a loop.
The color of the rectangles are provided from an array.
I want on clicking one of the rectangles, that background fills with the color I selected.
I'm new to processing so i'm a bit confused on how to do it.
color[] backgrounds = {#e8be55, #ff8827, #eb5051, #00b4cc, #005f6b, #7c6753, #edeaee};
int bgLength = backgrounds.length;
int xPos;
int yPos;
int size;
void setup(){
background(255);
size(1024, 768);
}
void draw(){
size = 40;
xPos = guide + 10;
yPos = 167;
for(int i = 0; i < bgLength; i++) {
noStroke();
fill(backgrounds[i]);
rect(xPos, yPos, size, size);
xPos = xPos + size + 4;
if(xPos>180){
xPos = guide + 10;
yPos += size + 4;
}
}
}
Thanks.
You need to check the bounds. First I suggest you organize the variables a bit.
For example some variables never change(so there's no reason to assign them in draw()).
This should make it easier to see what the coordinates are.
I suggest this:
color[] backgrounds = {#e8be55, #ff8827, #eb5051, #00b4cc, #005f6b, #7c6753, #edeaee};
int bgLength = backgrounds.length;
int xOffset = 10;
int yOffset = 167;
int xPos;
int yPos;
int size = 40;
int guide = 10;
int cols = 4;//4 columns
color selectedBackground = backgrounds[backgrounds.length-1];//default to last element in the list/array
void setup(){
background(255);
size(1024, 768);
noStroke();
}
void draw(){
background(selectedBackground);
for(int i = 0; i < bgLength; i++) {
xPos = xOffset + ((i % cols) * (size+guide));//since % is returns the remainder of division, we use it to compute x position in the grid
yPos = yOffset + ((i / cols) * (size+guide));//and we divide by the number of columns to compute the y position in the grid
fill(backgrounds[i]);
//check if a box is clicked
if((mouseX >= xPos && mouseX <= xPos+size) && //check horizontal bounds(left/right)
(mouseY >= yPos && mouseY <= yPos+size)){ //check vertical bounds(top/bottom)
if(mousePressed){//if mouse is over/within a boxes bounds and clicked
selectedBackground = backgrounds[i];//set the colour based on id
}else{//just hovering
fill(backgrounds[i],127);//draw transparent colour, just to high light selection, not actually needed, but now an easy option
}
}
rect(xPos, yPos, size, size);//we draw at the end because the fill colour might have changed if a box was hovered
}
}
You can run a javascript demo bellow. (Although there are minor differences in syntax, the core concept is the same):
var backgrounds;// = [color('#e8be55'), color('#ff8827'), color('#eb5051'), color('#00b4cc'), color('#005f6b'), color('#7c6753'), color('#edeaee')];
var bgLength;// = backgrounds.length;
var xOffset = 10;
var yOffset = 67;
var xPos = 0;
var yPos = 0;
var ssize = 40;
var guide = 10;
var cols = 4;//4 columns
var selectedBackground;// = backgrounds[backgrounds.length-1];//default to last element in the list/array
function setup(){
createCanvas(1024, 768);noStroke();
backgrounds = [color('#e8be55'), color('#ff8827'), color('#eb5051'), color('#00b4cc'), color('#005f6b'), color('#7c6753'), color('#edeaee')];
bgLength = backgrounds.length;
selectedBackground = backgrounds[backgrounds.length-1];//default to last element in the list/array
}
function draw(){
background(selectedBackground);
for(var i = 0; i < bgLength; i++) {
xPos = xOffset + ((i % cols) * (ssize+guide));//since % is returns the remainder of division, we use it to compute x position in the grid
yPos = yOffset + (floor(i / cols) * (ssize+guide));//and we divide by the number of columns to compute the y position in the grid
fill(backgrounds[i]);
//check if a box is clicked
if((mouseX >= xPos && mouseX <= xPos+ssize) && //check horizontal bounds(left/right)
(mouseY >= yPos && mouseY <= yPos+ssize)){ //check vertical bounds(top/bottom)
if(isMousePressed){//if mouse is over/within a boxes bounds and clicked
selectedBackground = backgrounds[i];//set the colour based on id
}else{//just hovering
fill(backgrounds[i].rgba[0]+50,backgrounds[i].rgba[1]+50,backgrounds[i].rgba[2]+50);//draw transparent colour, just to high light selection, not actually needed, but now an easy option
}
}
rect(xPos, yPos, ssize, ssize);//we draw at the end because the fill colour might have changed if a box was hovered
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.4/p5.min.js"></script>

Resources