Thursday, October 1, 2020

prevent browser scrolling / dragging while drawing on canvas on mobile

I'm making a minimalist shared whiteboard app using p5 / p5.js, which is my favorite way of doing canvas tag stuff. Believe it or not this is a runnable drawing program in p5:

function setup() {
  createCanvas(400, 400);
}

function mouseDragged(){
  line(pmouseX,pmouseY, mouseX,mouseY)
}

Anyway, the program, with a PHP backend, was coming along fine, but was frustrating on my phone and tablet - the same events to draw on the canvas would drag the whole window (even though there was no need to scroll, all the content of the page was visible.) How to ignore finger scrolling in these cases?  (grep bait: block drag scroll event p5 ignore disable)

Tried some CSS trickery - the most promising was making it "position:fixed;" but somehow the touch events were being scaled vertically (I think the page was being moved behind the canvas, and somehow that was where the x and y were being calculated from)

As always, stackoverflow to the rescue. I ended up making a function like this:

function stopTouchScrolling(canvas){
// Prevent scrolling when touching the canvas
document.body.addEventListener("touchstart", function (e) {
    if (e.target == canvas) {
        e.preventDefault();
    }
}, { passive: false });
document.body.addEventListener("touchend", function (e) {
    if (e.target == canvas) {
        e.preventDefault();
    }
}, { passive: false });
document.body.addEventListener("touchmove", function (e) {
    if (e.target == canvas) {
        e.preventDefault();
    }
}, { passive: false });

}

To call that in p5, I had to retrieve the actual canvas DOM element. There might be an easier way, but setting the id of the canvas and then using the plain old document.getElementById() worked fine:

  createCanvas(800,800).parent("canvasParent").id("drawingCanvas");
  stopTouchScrolling(document.getElementById('drawingCanvas'));

Works great on iPhone, iPad, and I had a buddy test it out on Android Edge and chrome.

No comments:

Post a Comment