Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent scrolling during html5 canvas touchmove event

How do I prevent scrolling without preventing default, because I still want the touchmove event to be processed:

    <!DOCTYPE html>
    <html>
    <head>
      <script src="jquery.min.js"></script>
    </head>
    <body>
    <canvas id="myCanvas" width="1600px" height="1600px" style="border:1px dashed gray;background-color:white;">
    </canvas>

    <script>

    function brushStart() {
      $('#myCanvas').css('background-color','blue');  
    }
    function brushEnd() {
      $('#myCanvas').css('background-color','red');   
    }
    function brushMove() {
      $('#myCanvas').css('background-color','yellow');  
    }

    $('#myCanvas').bind('mousedown', brushStart);
    $('#myCanvas').bind('mouseup', brushEnd);
    $('#myCanvas').bind('mousemove', brushMove);
    $('#myCanvas')[0].addEventListener('touchstart',brushStart,false);
    $('#myCanvas')[0].addEventListener('touchend',brushEnd,false);
    $('#myCanvas')[0].addEventListener('touchmove',brushMove,false);

    </script>

    </body>
    </html>
like image 774
Homan Avatar asked Mar 21 '12 18:03

Homan


1 Answers

When you say you want it to be processed - it still can be. Just write it like this:

$('#myCanvas')[0].addEventListener('touchmove', function(e) {
  e.preventDefault();
  brushMove();
},false);

I don't guarantee that preventDefault alone will stop the scrolling, but that's how you'd write it if you wanted it to prevent the default and do your own method too. You could also put the call in brushMove itself.

Let me just say that you probably need to be doing preventDefault in touchStart and not touchMove. touchMove might actually be too late, because if it is scrolling there might be no touchMove events to be had!

like image 77
Simon Sarris Avatar answered Sep 22 '22 12:09

Simon Sarris