javascripthtmltypescriptdomtouch

js TouchEvent: when pinching with two fingers and lifting one of them up, how to kown which finger had lifted?


i'am working in a complicated touching gesture, and meet this problem:

let cachedStartTouches: TouchList;
let cachedMoveTouches: TouchList;

function onStart(ev: TouchEvent) {
  // length equals 2 when two fingers pinch start
  cachedStartTouches = ev.touches;
}

function onMove(ev: TouchEvent) {
  // length equals 2 when two fingers pinching moving
  cachedMoveTouches = ev.touches; 
}

function onEnd(ev: TouchEvent) {
  // equals 1 when one finger holds up early, but another one still moving
  ev.touches.length

  // the cachedTouches's length is still two now,  
  // how to known which idx had been canceled, 0 or 1 ?
  const idx = getCanceledTouchesIdx(????)

  // remove it from cache
  cachedStartTouches.splice(idx, 1)
  cachedMoveTouches.splice(idx, 1)
}

more genral case: N fingers pinching, and lifting some of them?


Solution

  • The TouchEvent has:

    In the case of the touch end event this means that the ended touches can be read from the event.changedTouches list, while the remaining touches will be in the event.touches list.

    Alternatively you can keep track of event.touches in start / move event handlers and see which touches disappear from the event.touches list in the end event handler.

    Side note: you can differentiate touches using touch.identifier


    It may be easier to work with touches if they were an array, so as a bonus here's my helper function:

    export const touchListToArray = (touches: TouchList) =>
    {
        const array = new Array<Touch>(touches.length);
        for (let i = 0; i < touches.length; ++i)
        {
            array[i] = touches.item(i);
        }
        return array;
    };