xxxxxxxxxx
60
let colns = []; //array for columns
function setup() {
createCanvas(400, 400); // create 400x400 canvas
// single loop function to draw 20 columns
for (let i = 0; i < 20; i++) {
//define the intital position of the 1st column
colns.push(new Coln(i * width / 20, 0, width / 20, height));
}
}
function draw() {
background(225); // draw background in white
// declare a new variable for each iteration of new drawn columns
for (let coln of colns) {
coln.display(); // call: display
coln.checkMouse(); // call: checkMouse
}
}
function mousePressed() { // when the user presses a mouse button
// declare a new variable for each iteration of new drawn columns
for (let coln of colns) {
coln.reset(); // call: reset
}
}
class Coln { // defines a new class for each columns
// declare 4 parameters for runs when a new object of the class Colns
constructor(x, y, w, h) {
this.x = x; // variable for x position
this.y = y; // variable for y position
this.w = w; // variable for column's width
this.h = h; // variable for column's height
this.revealed = false; // Tracks if the column is revealed by using boolean expression
this.color = 'white'; // assign color white to color variable
}
display() { // draw columns
noStroke(); // Removes the stroke
fill(this.color); // assign color with color variable
rect(this.x, this.y, this.w, this.h); // draw columns with x,y,w,h variables
}
checkMouse() { // declare function to check if the mouse is over the column
// If mouse is over the column, reveal it
if (mouseX > this.x && mouseX < this.x + this.w) {
this.revealed = true; // update boolean expression if mouse is over the column
let colorg = map(mouseX, 0, width, 0, 255); // assign green color value by mapping mouseX
let colorb = map(mouseX, 0, width, 255, 0); // assign blue color value by mapping mouseX
this.color = color(0, colorg, colorb); // update each column's color
}
}
reset() { // Reset column colors on click
this.revealed = false; // return boolean expression to false
this.color = 'white'; // update and return each column's color to white
}
}