Homan
Homan

Reputation: 26718

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>

Upvotes: 6

Views: 8408

Answers (1)

Simon Sarris
Simon Sarris

Reputation: 63812

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!

Upvotes: 7

Related Questions