HTML5 Game - Canvas Event Touch position

Introduction

The following code shows the touch position:

Demo

ResultView the demo in separate window

<!doctype html>  
    <html>  
     <head>  
      <meta charset="utf-8">  
      <title>Touch Events</title>  
    <style>#canvas {
  background-color: grey;
}</style>//from ww w.ja va  2s.  co  m
     </head>  
     <body>  
      <canvas id="canvas" width="400" height="400"></canvas>  
      <script>  
        
        function captureTouch(element) {
  let touch = {x: null, y: null, isPressed: false, event: null},
      body_scrollLeft = document.body.scrollLeft,
      element_scrollLeft = document.documentElement.scrollLeft,
      body_scrollTop = document.body.scrollTop,
      element_scrollTop = document.documentElement.scrollTop,
      offsetLeft = element.offsetLeft,
      offsetTop = element.offsetTop;

  element.addEventListener('touchstart', function (event) {
    touch.isPressed = true;
    touch.event = event;
  }, false);

  element.addEventListener('touchend', function (event) {
    touch.isPressed = false;
    touch.x = null;
    touch.y = null;
    touch.event = event;
  }, false);
  
  element.addEventListener('touchmove', function (event) {
    let x, y,
        touch_event = event.touches[0]; //first touch
    
    if (touch_event.pageX || touch_event.pageY) {
      x = touch_event.pageX;
      y = touch_event.pageY;
    } else {
      x = touch_event.clientX + body_scrollLeft + element_scrollLeft;
      y = touch_event.clientY + body_scrollTop + element_scrollTop;
    }
    x -= offsetLeft;
    y -= offsetTop;
    
    touch.x = x;
    touch.y = y;
    touch.event = event;
  }, false);
  
  return touch;
}

      window.onload = function () {  
        let canvas = document.getElementById('canvas');  

        function onTouchEvent (event) {  
          console.log(event.type);  
        }  
    let canvas = document.getElementById('canvas'),  
        touch = captureTouch(canvas);  
    if (touch.isPressed) {  
      console.log("x: " + touch.x + ", y: " + touch.y);  
    }  
    
        canvas.addEventListener('touchstart', onTouchEvent, false);  
        canvas.addEventListener('touchend', onTouchEvent, false);  
        canvas.addEventListener('touchmove', onTouchEvent, false);  
      };  
      </script>  
     </body>  
    </html>

Related Topic