Skip to content

Instantly share code, notes, and snippets.

@alejandrofloresm
Created October 11, 2019 00:18
Show Gist options
  • Select an option

  • Save alejandrofloresm/a8d6f76ffc61b2a4190e52b4371adee9 to your computer and use it in GitHub Desktop.

Select an option

Save alejandrofloresm/a8d6f76ffc61b2a4190e52b4371adee9 to your computer and use it in GitHub Desktop.
Simple Button Class for p5.js
class Button {
constructor(label, x, y, colorHex = '#FF0000') {
this.label = label;
this.x = x;
this.y = y;
this.colorHex = colorHex;
this.labelSize = textWidth(label);
this.spacing = 20;
this.width = this.labelSize + this.spacing;
this.height = 25;
this.normalBg = color(colorHex);
this.normalFg = this.contrastColor(this.normalBg);
this.hoverBg = this.normalFg;
this.hoverFg = this.normalBg;
this.hover = false;
this.clicked = false;
}
draw() {
push();
noStroke();
fill(!this.hover ? this.normalBg : this.hoverBg);
rect(this.x, this.y, this.width, this.height);
fill(!this.hover ? this.normalFg : this.hoverFg);
text(this.label,
this.x + this.spacing * 0.5,
this.y + 17);
pop();
}
mousePressed(cb) {
if (this.hover) {
cb();
}
}
mouseMoved() {
this.hover = this.checkIfMouseIsOverButton();
}
checkIfMouseIsOverButton() {
let x = mouseX;
let y = mouseY;
let result = false;
if (x > this.x &&
x < this.x + this.width &&
y > this.y &&
y < this.y + this.height)
{
result = true;
}
return result;
}
contrastColor(theColor) {
let r = red(theColor);
let g = green(theColor);
let b = blue(theColor);
let luma = ((0.299 * r) + (0.587 * g) + (0.114 * b)) / 255;
return luma < 0.5 ? color('#FFF') : color('#000');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment