2010-09-11 51 views
5

我在html5画布上制作游戏。我使用jquery,所以我可以得到点击事件和点击x,y坐标。我有一个单位对象和平铺地形(也是一个数组)的数组。单位对象具有边界框信息,它们的位置和类型。确定屏幕上的哪个对象在html5 canvas javascript中被点击?

将此点击事件映射到其中一个单元的最有效方法是什么?

+0

我想也许我只是做这样的事情:if(elements.bound.left e.pageX) – Travis 2010-09-11 11:20:21

+0

你可能会考虑使用svg作为对象和画布仅用于背景和效果。您可以免费使用类似$(“。projectile”),live(“click”,..)的东西,然后浏览器将处理z-index计算和精确交集本身。 – artificialidiot 2010-09-11 11:26:23

回答

5

循环遍历单位对象,并确定所单击像这样:

// '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` 

注意,这不会处理复杂的交叉对象或z-index的问题等等......只是一个起点真的。