2010-09-11 10 views
5

Estoy haciendo un juego en lienzo html5. Estoy usando jquery para poder obtener el evento click y las coordenadas clics x, y. Tengo una matriz de objetos de unidad y un terreno de mosaico (también una matriz). Los objetos de la unidad tienen información de cuadro delimitador, su posición y su tipo.Identifique qué objeto en la pantalla hizo clic en html5 canvas javascript?

¿Cuál es la forma más eficiente de asignar este evento de clic a una de las unidades?

+0

Me imagino que acabo de hacer algo como esto: if (elements.bound.left e.pageX) – Travis

+0

Puede considerar el uso de svg para objetos y lienzo solo para fondo y efectos. Obtendrá usar algo como $ ("proyectil") en vivo ("clic", ...) de forma gratuita, luego el navegador manejará el cálculo del índice Z y la intersección exacta. – artificialidiot

Respuesta

5

bucle a través de los objetos de la unidad y determinar qué se ha hecho clic, así:

// 'e' is the DOM event object 
// 'c' is the canvas element 
// 'units' is the array of unit objects 
// (assuming each unit has x/y/width/height props) 

var y = e.pageY, 
    x = e.pageX, 
    cOffset = $(c).offset(), 
    clickedUnit; 

// Adjust x/y values so we get click position relative to canvas element 
x = x - cOffset.top; 
y = y - cOffset.left; 
// Note, if the canvas element has borders/outlines/margins then you 
// will need to take these into account too. 

for (var i = -1, l = units.length, unit; ++i < l;) { 
    unit = units[i]; 
    if (
     y > unit.y && y < unit.y + unit.height && 
     x > unit.x && x < unit.x + unit.width 
    ) { 
     // Escape upon finding first matching unit 
     clickedUnit = unit; 
     break; 
    } 
} 

// Do something with `clickedUnit` 

Nota, esto no va a manejar objetos complejos o problemas de intersección z-index etc ... sólo un punto de partida realmente.