HTML5   发布时间:2022-04-25  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了确定屏幕上哪个对象点击了html5 canvas javascript?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在用 html5画布制作游戏.我正在使用 jquery,@R_457_9447@获得click事件和点击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问题等……只是一个真正的起点.

大佬总结

以上是大佬教程为你收集整理的确定屏幕上哪个对象点击了html5 canvas javascript?全部内容,希望文章能够帮你解决确定屏幕上哪个对象点击了html5 canvas javascript?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。