skip to Main Content

I am trying to add touch compatibility to my js game and need to know the location of the touch event on window object, With clicks you get e.x,e.y but there is no such property for touch start.

I tried to adjust the code but it not work , this is what im working with:

window.addEventListener('touchstart',(e)=>{
console.log(e.x,e.y)//error undefined or NaN
})

the same code works for:

window.addEventListener('click',(e)=>{
console.log(e.x,e.y)//works
})

I need this for the functionality of my game as i need to detect when the user is touching a sprite drawn on canvas and not a html element, I’m okay to use any other listeners but i need the to work on touchscreen.

How to get the location of the touch event???

2

Answers


  1. You can detect touch and obtain coordinates using this example:

    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);
    });
    
    Login or Signup to reply.
  2. Please change e.touches[0].clientX instead of e.x and e.touches[0].clientY instead of e.y.

    And if you get delta location or position, you can use this below method.

    deltaX = e.changedTouches[0].clientX - clientX;
    deltaY = e.changedTouches[0].clientY - clientY;

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search