Skip to main content

Phaser 3 Touch Scroll on Mobile

·1 min

While developing Math Command I ran into an issue where mobile users could not scroll the page. It turns out Phaser 3 captures all touch events on the canvas which prevents page scrolling.

The root cause is that Phaser automatically calls event.preventDefault() on all touch events. A workaround is to set game.input.touch.capture to false and manually call pointer.event.preventDefault(). This feels a little hacky but it will enable scrolling while touching the canvas on mobile devices.

var config = {
    type: Phaser.AUTO,
    parent: 'game',
    width: 800,
    height: 600,
    input: {
        touch: {
            capture: true
        }
    },
    scene: {
        create: create
    }
};

var game = new Phaser.Game(config);

function create () {
  // This prevents Phaser from applying event.preventDefault on all events
  game.input.touch.capture = false;

  var rect = this.add.rectangle(200, 200, 100, 100, 0xff0000);
  rect.setInteractive();
  rect.on('pointerup', (pointer) => {
    console.log('Pointer Up!');

    // Ensure event.preventDefault is added as it is no longer added automatically
    pointer.event.preventDefault();
  });
}

Setting capture to false in the config will also enable scroll in Chrome but will cause weird behavior on mobile devices. This is because the setting completely disables the manager instead of just the event.preventDefault() call. See https://github.com/photonstorm/phaser/blob/v3.22.0/src/input/touch/TouchManager.js#L246