4
I have a question when creating a button builder for Canvas in JS, I can already detect the click in the button area, but I would like to simplify the code with a constructor, to speed up my content creation process, but I have no idea how to do it.
Here’s an example of my code:
var bt = new Botao(0,0, 100, 50); // cria o botao
//construtor de botoes simples.
// eu utilizo um construtor de canvas por isso o parâmetro "canvas".
function Botao(x,y,w,h, canvas){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.render = function(){
canvas.context.fillRect(this.x,this.y,this.w,this.h);
}
}
// aqui eu detecto o click do usuário.
function click (evt) {
var rectNav = game.canvas.getBoundingClientRect(); //obtêm as coordenadas do mouse na janela do cliente.
var pos = {
x: evt.clientX - rectNav.left,
y: evt.clientY - rectNav.top
};
if(pos.x>bt.x && pos.x<(bt.x+bt.w) && pos.y>bt.y && pos.y<(bt.y+bt.h)) {
alert("click")}; // verifica se o click foi na area do botao "bt".
};
My question is: how do I put all this "click" detection code inside my button maker, where I can just call the function, for example, bt.click(codigo para ser executado)
within a function that I constantly update without having to create that additional code, and without having to create a eventListener
for such.
Grateful!