Determine which object on screen clicked in html5 canvas javascript?

I am making a game in html5 canvas. I am using jquery, so I can get the click event and clicks the x, y coordinates. I have an array of single objects and a tiled terrain (also an array). Single objects have information about the restrictive block, their position and their type.

What is the most efficient way to map a click event to one of the blocks?

+5
source share
1 answer

Scroll through the block objects and determine what was clicked like this:

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

Please note: this will not handle complex intersecting objects or problems with z-indexes, etc ... just a starting point.

+5
source

All Articles