简体   繁体   中英

How to handle touch events with html5 canvas?

I have created the painting based feature with html5 canvas. When it comes to the desktop it's working as I expected, but the problem only in touch devices. I'm clueless where is the issues are coming from. Can someone help me to fix this one? I'm struggling with past two days.

My code

if(windowWidth <= 1024) {
  canvas2.addEventListener('touchmove', function(e) {
      mouse.x = e.pageX;
      mouse.y = e.pageY;
      handlerPos.x = e.pageX;
      handlerPos.y = e.pageY;
  }, false);
} else {
  canvas2.addEventListener('mousemove', function(e) {
    mouse.x = e.pageX;
    mouse.y = e.pageY;
    handlerPos.x = e.pageX;
    handlerPos.y = e.pageY;
  }, false);
}

Maybe you are looking for this

Unfortunately, all was not well. An issue arose from a conflict with built-in browser gestures. When I moved my finger on the canvas, I wanted the page to stay still so I could draw. However, if my page had horizontal or vertical scrolling (and it did) the page would move along with my finger and making proper drawing impossible. After some frustration, I stumbled upon the solution: preventing scrolling on document.body if the target of a touch event is the canvas.

http://bencentra.com/code/2014/12/05/html5-canvas-touch-events.html

document.body.addEventListener('touchmove', function(e) {
   mouse.x = e.pageX;
   mouse.y = e.pageY;
   handlerPos.x = e.pageX;
   handlerPos.y = e.pageY;
}, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM