【问题标题】:Identify which object on screen clicked in html5 canvas javascript?确定在 html5 canvas javascript 中点击了屏幕上的哪个对象?
【发布时间】:2010-09-11 19:24:52
【问题描述】:

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

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

【问题讨论】:

  • 我想也许我只是做这样的事情:if(elements.bound.lefte.pageX)
  • 您可以考虑将 svg 用于对象,将画布仅用于背景和效果。您将可以免费使用 $(".projectile").live("click",..) 之类的东西,浏览器将自行处理 z-index 计算和精确交集。

标签: javascript html canvas


【解决方案1】:

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

// '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 问题等...实际上只是一个起点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多