我正在尝试向我的 js 游戏添加触摸兼容性,并且需要知道窗口对象上触摸事件的位置,通过单击您会得到 e.x,e.y,但触摸启动没有这样的属性。
我尝试调整代码,但它不起作用,这就是我正在处理的内容:
window.addEventListener('touchstart',(e)=>{
console.log(e.x,e.y)//error undefined or NaN
})
相同的代码适用于:
window.addEventListener('click',(e)=>{
console.log(e.x,e.y)//works
})
我需要这个来实现我的游戏功能,因为我需要检测用户何时触摸绘制在画布上的精灵而不是 html 元素,我可以使用任何其他侦听器,但我需要在触摸屏上工作。
如何获取触摸事件的位置???
您可以使用此示例检测触摸并获取坐标:
window.addEventListener('touchstart', (e) => {
const touch = e.touches[0]; // e.touches is an array containing all touches
const x = touch.clientX;
const y = touch.clientY;
alert('X: '+x +', Y: '+ y);
});