API . ,
.
. , .
:
:
function canvasButton(x, y, w, h, style , text) {
this.style = style
this.x = x || 0;
this.y = y || 0;
this.w = w || 1;
this.h = h || 1;
this.fill = style.default.fill ;
this.text = text || undefined;
this.onclick = function() {alert("Click! Make sure to add the onclick listener to your button!")}
this.mouseup = function() {alert("Mouseup! Make sure to add the mouseup listener to your button!")}
this.addListener = function() {
var buttonX = this.x;
var buttonY = this.y;
var buttonWidth = this.w;
var buttonHeight = this.h;
var onclick = this.onclick
var mouseup = this.mouseup
var styles = this.style
var draw = this.draw
var ctx = this.ctx
this.ctx.canvas.addEventListener('mousedown',function(e){
var click_x = e.clientX;
var click_y = e.clientY;
if ( click_x >= buttonY && click_x <= buttonX + buttonWidth && click_y >= buttonY && click_y <= buttonY + buttonHeight ) {
onclick()
ctx.fillStyle = style.active.fill
ctx.fillRect(buttonX, buttonY, buttonWidth, buttonHeight);
}
})
this.ctx.canvas.addEventListener('mouseup',function(e) {
var click_x = e.clientX;
var click_y = e.clientY;
if ( click_x >= buttonY && click_x <= buttonX + buttonWidth && click_y >= buttonY && click_y <= buttonY + buttonHeight ) {
mouseup()
ctx.fillStyle = style.default.fill
ctx.fillRect(buttonX, buttonY, buttonWidth, buttonHeight);
}
})
}
}
canvasButton.prototype.draw = function(ctx) {
this.ctx = ctx
ctx.fillStyle = this.fill;
ctx.font = this.font
ctx.fillRect(this.x, this.y, this.w, this.h);
ctx.fillText(this.text,this.x,this.y)
this.addListener();
}
var start = new canvasButton(x,y,height,width,{
"default": {
"fill":"#765",
},
"active": {
"fill":"#876",
}
})
start.mousedown = function() {
}
start.mouseup = function() {
}
start.draw(document.getElementById("canvas").getContext("2d"));
source
share