Replace mousemove with touchmove event

2.6k Views Asked by At

My program recognizes the mousemove event. What I would like to do is make my program work for mobile.

That is why I would like to transform the mousemove event to a touchmove event.

My code is like this so far:

var d=ctx.getImageData(0,0,canvas.width,canvas.height).data;
$hit=$("#hit");
$("#canvas").mousemove(function(e){handleMouseMove(e);});

tolerance = 20;
function handleMouseMove(e){

  e.preventDefault();
  e.stopPropagation();
  mouseX=parseInt(e.clientX-offsetX);
  mouseY=parseInt(e.clientY-offsetY);
  var isHit=d[(mouseY*cw+mouseX)*4+3]>tolerance;

  if(isHit){
    $hit.text("Yeahhhh");
  }else{
    //document.onmousemove = crash;
    $hit.text("Noooooooo");
  }
}

Is there a way that I can do that easily?

I have read that is equivalent When to use touchmove vs mousemove? but I am not sure how to handle the mouseX and the mouseY.

2

There are 2 best solutions below

0
On

You can use jQuery UI Touch Punch for hack jquery events

read this:http://touchpunch.furf.com/

0
On

toe.js - a lightweight touch events library, works pretty well. Hammerjs definitely has more customization, but toejs looked simpler.

and have a suggestion in your code to avoid unnecessary event.stopPropagation, see here.