Multiple touch events


Use your fingers or mouse to control the model (hold shift key or use mouse wheel to zoom it). Canvas is matched to your browser window.

3Kb Controls.js "library" is used to control models. Touch Event Test was very useful for touch events undestanding.

var gl, canvas,  pi180 = 180/Math.PI,
  transl = -3, rTouch, fiTouch, idTouch0,
  xRot = yRot = zRot =  xOffs = yOffs =  drag = 0;
function startTouch(evt) {
  var evList = evt.touches;
  if(evList.length == 1){                // one finger touch
    xOffs = evList[0].pageX;  yOffs = evList[0].pageY;
    drag = 1;}
  else if(evList.length == 2){           // two fingers touch
    idTouch0 = evList[0].identifier;
    var dx = evList[1].pageX - evList[0].pageX;
    var dy = evList[1].pageY - evList[0].pageY;
    rTouch = Math.sqrt(dx*dx + dy*dy);   // 2 fingers radius
    fiTouch = Math.atan2(dy, dx);        // 2 fingers angle
    drag = 2;}
  evt.preventDefault();
}
function continueTouch(evt) {
  if(drag == 1){                         //  X, Y - rotations
    var x = evt.touches[0].pageX,  y = evt.touches[0].pageY;
    yRot = x - xOffs;  xRot = x - yOffs;
    xOffs = x;  yOffs = y;
    drawScene();}
  else if(drag == 2){                    //  zoom and Z - rotation
    var dx = evt.touches[1].pageX - evt.touches[0].pageX;
    var dy = evt.touches[1].pageY - evt.touches[0].pageY;
    var r = Math.sqrt(dx*dx + dy*dy);
    var fi;
    if( idTouch0 == evt.touches[0].identifier ) fi = Math.atan2(dy, dx);
    else fi = Math.atan2(-dy, -dx);
    transl *= rTouch / r;
    zRot = pi180*(fiTouch - fi);
    rTouch = r;  fiTouch = fi;
    drawScene();
  }
}
function stopTouch() {
  drag = 0;
}
...
function initGL(){
...
   canvas.addEventListener('touchstart', startTouch, false);
   canvas.addEventListener('touchmove', continueTouch, false);
   canvas.addEventListener('touchend', stopTouch, false);
}

WebGL examples     updated 30 Jan 2013