touch events tests

canvas. ref: https://developer.mozilla.org/en-US/docs/Web/API/Touch_events

by Anov Siradj

HTML

<canvas id="canvas" width="400" height="400" style="border:solid black 1px;">
  You really badly need to use a different browser.
</canvas>
<br>
<button onclick="window.startup();">Initialize</button>
<br>
Log: <pre id="log" style="border: 1px solid #ccc;"></pre>

CSS

body {
    padding: 50px;
    font-family: sans-serif;
}

#box {
    width:  100px;
    height: 100px;
    background-color: red;
}

JavaScript

function startup() {
  var el =document.body;
  el.addEventListener("touchstart", handleStart, false);
  el.addEventListener("touchend", handleEnd, false);
  el.addEventListener("touchcancel", handleCancel, false);
  el.addEventListener("touchleave", handleEnd, false);
  el.addEventListener("touchmove", handleMove, false);
  log("initialized.");
}
var ongoingTouches = new Array;
function handleStart(evt) {
    
 
//  log("touchstart.");
  var el = document.getElementsByTagName("canvas")[0];
  var ctx = el.getContext("2d");
  var touches = evt.changedTouches;
var offset = findPos(el);  
    
   
  for (var i = 0; i < touches.length; i++) {
      if(touches[i].clientX-offset.x >0 && touches[i].clientX-offset.x < parseFloat(el.width) && touches[i].clientY-offset.y >0 && touches[i].clientY-offset.y < parseFloat(el.height)){
            evt.preventDefault();
    log("touchstart:" + i + "...");
    ongoingTouches.push(copyTouch(touches[i]));
    var color = colorForTouch(touches[i]);
    ctx.beginPath();
    ctx.arc(touches[i].clientX-offset.x, touches[i].clientY-offset.y, 4, 0, 2 * Math.PI, false); // a circle at the start
    ctx.fillStyle = color;
    ctx.fill();
    log("touchstart:" + i + ".");
  }
  }
}
function handleMove(evt) {

  var el = document.getElementsByTagName("canvas")[0];
  var ctx = el.getContext("2d");
  var touches = evt.changedTouches;
  var offset = findPos(el);

  for (var i = 0; i < touches.length; i++) {
        if(touches[i].clientX-offset.x >0 && touches[i].clientX-offset.x < parseFloat(el.width) && touches[i].clientY-offset.y >0 && touches[i].clientY-offset.y < parseFloat(el.height)){
              evt.preventDefault();
      var color = colorForTouch(touches[i]);
    var idx = ongoingTouchIndexById(touches[i].identifier);
    
    if (idx >= 0) {
      log("continuing touch " + idx);
      ctx.beginPath();
      log("ctx.moveTo(" + ongoingTouches[idx].clientX + ", " + ongoingTouches[idx].clientY + ");");
     ...