Search code examples
javascriptioscssmobilevertical-scrolling

Prevent scrolling on mobile on page with canvas


I've tried many solutions online, but for some reason, this page still moves around vertically when moving my touch on the canvas:

<html>  
<head>
<style>

html, body {
  overflow-x: hidden;
}

body {
  background-color: lightgray;
  position: relative;
}

body.noScroll { 
  overflow: hidden;
}

</style>
</head>
<body>
        <canvas id="myCanvas" style="touch-action: none;" width="800" height="800"></canvas><br>        

        <script>

            document.body.addEventListener("touchmove", getTouchPos)

            var canvas = document.getElementById('myCanvas')            
            var context = canvas.getContext('2d')   

            context.fillStyle = "#000";
            context.fillRect(0, 0, canvas.width, canvas.height);

            function getTouchPos(evt) {
                evt.preventDefault();
            }

        </script>   
    </body> 
</html>

Tested on iOS Safari.


Solution

  • Have you found this post yet? Disable scroll/swipe action for html canvas drawing on ios

    It led to the following link. Looks like there are multiple events you have to account for. you have to reference your canvas as a dom element as well to evaluate the target

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