JSFiddle - React, Tailwind, and code Playground
by João Vitor Scheuermann
HTML
https://jsfiddle.net/JScheuermann/4hkb9xus/#update
JavaScript
// construtor de canvas
function Canvas(cWidth, cHeigth, canvasID, M) {
this.canvas = document.createElement('canvas');
// Se uma altura/largura nao forem setados, o tamanho da tela é usado com base para o canvas.
this.canvas.width = cWidth || window.innerWidth - M;
this.canvas.height = cHeigth || window.innerHeight - M;
this.context = this.canvas.getContext('2d');
this.canvas.style.border = "1px solid";
this.canvas.id = canvasID; // or use name
document.body.appendChild(this.canvas);
//Limpa o canvas a cada frame.
this.upC = function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
//cria um retangulo (preguiça de escrever).
this.rect = function(x, y, w, h) {
this.context.fillRect(x, y, w, h);
}
this.rectNav = this.canvas.getBoundingClientRect()
}
// construtor de botoes
function Botao(x, y, w, h, canvas, callback, color) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.cb = callback;
this.color = color;
this.render = function() {
canvas.context.fillStyle = color || '#000';
canvas.rect(this.x, this.y, this.w, this.h);
}
this.ontarget = function(pos) {
if (pos.x > this.x && pos.x < (this.x + this.w) && pos.y > this.y && pos.y < (this.y + this.h)) {
this.cb(); // <-- meu problema.
};
}
var teste = new Canvas(400, 300, teste, 0);
var bt1 = new Botao(100, 100, 100, 100, teste, function() {
console.log("teste");
});
function run() {
teste.upC();
bt1.render(); // renderiza o botao.
window.requestAnimationFrame(run);
}
run();
function click(evt) {
var rectNav = teste.rectNav;; //obtêm as coordenadas do mouse na janela do cliente.
var pos = {
x: evt.clientX - rectNav.left,
y: evt.clientY - rectNav.top
};
bt1.ontarget(pos); //detecta se o click foi no botão
}
cEvent('click', click);