确定屏幕上哪个对象点击了html5 canvas javascript?

Tra*_*vis 5 javascript html5 canvas

我正在用html5画布制作游戏.我正在使用jquery,所以我可以获得click事件和点击x,y坐标.我有一组单位对象和一个平铺地形(也是一个数组).单位对象具有边界框信息,它们的位置和类型.

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

Jam*_*mes 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`
Run Code Online (Sandbox Code Playgroud)

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