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

标签 javascript html canvas

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

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

最佳答案

循环遍历单元对象并确定哪个被点击,如下所示:

// '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 问题等...只是一个真正的起点。

关于javascript - 确定在 html5 canvas javascript 中点击了屏幕上的哪个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3690748/

相关文章:

javascript - 是否可以将 JavaScript 生成的图像保存在服务器端?

javascript - 为什么我的简单循环不能在 jsfiddle.net 中运行?

javascript - 在具有元素大小的较小 div 中模拟 1920x1080 窗口

javascript - KineticJS .toImage() 从区域/组创建图像的正确方法

javascript - 如何将度值更改为实际的 x/y 位置变化?

javascript - HTML5 SVG vs Canvas 用于大量行?

javascript - 在 vs 代码中获取有关 javascript 中函数参数对象类型的智能感知

Javascript 隐藏和显示 div 的动态内容

html - 将 div 叠加到图像的尺寸

javascript - 两个 div 彼此相邻,内容从第二个 div 换行