I'm having 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 streamline my process content, but I have no idea how to do it.
Here is 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 of this "click" detection code inside my button designer, where I can just call the function, for example, bt.click(codigo para ser executado)
inside a function that I constantly update without having to create this additional code, and without having to create a eventListener
to do so.
Thank you!