xxxxxxxxxx
112
class Button {
constructor(_x, _y, _colorArray = null) {
this.x = _x;
this.y = _y;
this.w = random(50, 100);
this.h = 50;
this.state = 0;
this.hover = 0;
// check if there's a _colorArray parameter
if (_colorArray) {
// create a copy
this.colors = _colorArray.slice();
} else {
// some default colors
this.colors = [color(230, 0, 30), color(30, 230, 0)];
}
}
reset() {
this.state = 0;
}
draw() {
let fillColor = this.colors[this.state];
let mColorR = max(red(fillColor) - 30 * this.hover, 0);
let mColorG = max(green(fillColor) - 30 * this.hover, 0);
let mColorB = blue(fillColor);
fill(mColorR, mColorG, mColorB);
rect(this.x, this.y, this.w, this.h, 5);
fill(0);
let bText = this.state == 0 ? "OFF" : "ON";
text(bText, this.x, this.y, this.w, this.h);
}
isUnderMouse() {
return (
mouseX > this.x &&
mouseX < this.x + this.w &&
mouseY > this.y &&
mouseY < this.y + this.h
);
}
checkHover() {
let mHover = this.isUnderMouse();
this.hover = mHover ? 1 : 0;
}
checkClick() {
let mHover = this.isUnderMouse();
this.state = mHover ? 1 - this.state : this.state;
}
}
let NUM_BUTTONS = 5;
let mButtons;
let toggleColors;
function setup() {
createCanvas(400, 400);
textAlign(CENTER, CENTER);
mButtons = [];
for (let bc = 0; bc < NUM_BUTTONS; bc++) {
let mX = random(0, width - 100);
let mY = random(0, height - 50);
mButtons.push(new Button(mX, mY));
}
let specialColors = [color("mediumpurple"), color("gold")];
mButtons.push(new Button(30, 220, specialColors));
specialColors = [color("steelblue"), color("deeppink")];
mButtons.push(new Button(150, 220, specialColors));
specialColors = [color("white"), color("violet")];
mButtons.push(new Button(280, 220, specialColors));
}
function draw() {
background(220);
for (let bi = 0; bi < mButtons.length; bi++) {
mButtons[bi].draw();
}
}
function mouseMoved() {
for (let bi = 0; bi < mButtons.length; bi++) {
mButtons[bi].checkHover();
}
}
function mouseClicked() {
for (let bi = 0; bi < mButtons.length; bi++) {
mButtons[bi].checkClick();
}
}
function keyReleased() {
if (key == "r" || key == "R") {
for (let bi = 0; bi < mButtons.length; bi++) {
mButtons[bi].reset();
}
}
}