xxxxxxxxxx
48
let b1;
function setup() {
createCanvas(400, 400);
bg = color(200);
b1 = new Button(100, 100, 80, 30, "press", color(0, 255, 0), color(0, 200, 0), function() {
background(255, 0, 255);
});
print("see https://discourse.processing.org/t/p5-js-how-to-use-a-function-as-an-object-parameter/14753");
}
function draw() {
background(200);
b1.draw();
}
//________________________________________________ CLASS BUTTON
const Button = class {
constructor(ixp, iyp, iw, ih, itext, icolor1, icolor2, ido) {
this.w = iw; // button width
this.h = ih; // button height
this.posX = ixp; // button x postion
this.posY = iyp; // button y position
this.text = itext; // button label
this.color1 = icolor1; // button default color
this.color2 = icolor2; // button color when under mouse
this.do = ido; // user function
print("use mousePress on button");
}
draw() {
this.check_click();
fill(this.color1); // rect fill
rect(this.posX, this.posY, this.w, this.h);
fill(0, 0, 200); // text color
stroke(0, 0, 200);
textAlign(CENTER);
text(this.text, this.posX + this.w / 2, this.posY + this.h / 2 + 5);
}
over() {
return (
mouseX > this.posX && mouseX < this.posX + this.w &&
mouseY > this.posY && mouseY < this.posY + this.h )
}
check_click() {
if ( mouseIsPressed && this.over() ) this.do();
}
}