var WHITE = color(255, 255, 255); var BLACK = color(0, 0, 0); var RED = color(255, 0, 0); var GREEN = color(0, 255, 0); var BLUE = color(0, 0, 255); var YELLOW = color(255, 255, 0); var CYAN = color(0, 255, 255); var MAGENTA = color(255, 0, 255); //Define standard colours var buttons = []; //Set up buttons array for filling later var mousePressed = function() { for(var i in buttons) { buttons[i].checkClick(); } }; var mouseReleased = function() { for(var i in buttons) { buttons[i].mouse = false; } }; var Button = function(x, y, w, h, r, ncolour, hcolour, ccolour, normal, callback, callbackParam, debug) { this.x = x; this.y = y; this.w = w; this.h = h; this.r = r; this.ncolour = ncolour; this.hcolour = hcolour; this.ccolour = ccolour; this.normal = normal; this.callback = callback; this.callbackParam = callbackParam; this.state = this.normal; this.debug = debug; this.mouse = false; this.canCallback = true; }; Button.prototype.get = function() { return this.state; }; Button.prototype.checkMouse = function() { if(mouseX >= this.x && mouseX <= this.x + this.w && mouseY >= this.y && mouseY <= this.y + this.h && !mouseIsPressed) { this.mouseOver = true; } else { this.mouseOver = false; } }; Button.prototype.checkClick = function() { this.mouse = false; if(this.mouseOver) { this.mouse = true; } }; Button.prototype.checkStatus = function() { this.state = this.normal; if(this.mouseOver) { this.state = !this.state; } }; Button.prototype.setColour = function() { fill(this.ncolour); if(this.mouse) { fill(this.ccolour); } else if(this.state) { fill(this.hcolour); } }; Button.prototype.update = function() { this.checkMouse(); this.checkStatus(); this.setColour(); rect(this.x, this.y, this.w, this.h, this.r); if(this.mouse && this.canCallback) { this.canCallback = false; if(this.callback !== null) { this.callback(this.callbackParam); } } if(!this.mouse) { this.canCallback = true; } if(this.debug) { fill(255, 0, 0); this.debugText = []; for(var i in this) { this.do = true; this.disallowed = ["constructor", "get", "callback", "setColour", "update", "__id", "checkStatus", "checkMouse", "checkClick"]; for(var j in this.disallowed) { if(i === this.disallowed[j]) { this.do = false; } } if(this.do) { this.debugText.push(this[i]); } } text(this.debugText, this.x, this.y); } }; var printData = function(data) { println(data); }; for(var i = 0; i < 5; i++) { buttons.push(new Button(0, i * 20, 20, 20, 5, GREEN, RED, CYAN, false, printData, "Button " + i, true)); } var draw = function() { background(WHITE); for(var i = 0; i < 5; i++) { buttons[i].update(); } };