我最近創建了一個用於檢測鼠標在矩形上的點擊的API。這是非常基本的,但它應該可以解決你的問題
你可以找到它here。
注:目前沒有針對按鈕文本的支持,但它確實有一些基本款式
支持 文檔: Here 代碼:
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);
}
})
}
}
// Draws this shape to a given context
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();
}
//Use it like this:
var start = new canvasButton(x,y,height,width,{ // Styles
"default": {
"fill":"#765",
},
"active": {
"fill":"#876",
}
})
//Event Listeners
start.mousedown = function() {
}
start.mouseup = function() {
}
start.draw(document.getElementById("canvas").getContext("2d")); // Draw to canvas
用於ASCII藝術! – 2012-10-12 03:14:07