xxxxxxxxxx
72
/*
* Creative Coding Workshop #4 Sample - Interactive Tiles
*
* Jack B. Du (github@jackbdu.com)
*/
// initialize global variables
let tiles = [];
let cols = 20;
let rows = 20;
let tileWidth;
let tileHeight;
function setup() {
createCanvas(400, 400);
tileWidth = width/cols;
tileHeight = height/rows;
// initialize a grid of tile objects
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
let x = c * tileWidth;
let y = r * tileHeight;
tiles.push(new Tile(x, y, tileWidth, tileHeight));
}
}
}
function draw() {
background(220);
// update and display each tile
for (let tile of tiles) {
tile.update();
tile.display();
}
}
// a class (template/blueprint) for tile
class Tile {
// constructor for initializing the object with these provided parameters
constructor(x, y, w, h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.baseColor = color(255);
this.c = this.baseColor;
}
// update color based on mouse positions
update() {
// test if mouse is within current tile
if (mouseX > this.x &&
mouseX < this.x+this.w &&
mouseY > this.y &&
mouseY < this.y+this.h) {
// assign a color based on current tile positions
this.c = color(map(sin(this.x/100),-1,1,0,255),
map(sin(this.x/200),-1,1,0,255),
map(sin(this.x/300),-1,1,0,255));
} else {
// assign a color by blending two colors
this.c = lerpColor(this.c, this.baseColor, 0.1);
}
}
// display current tile
display() {
noStroke();
fill(this.c);
rect(this.x, this.y, this.w, this.h);
}
}