Find safe area outside mobile notch in Phaser using CSS variables

If you are looking to create HUD elements for a game which is set to ENVELOP or FIT in your scale config, you want to avoid the display bleeding into the area on mobiles with a notch obscuring the display. To expose this in your Phaser game, add this to the CSS in the HTML file containing your Phaser canvas:

body {
  --safe-area-inset-top: env(safe-area-inset-top);
  --safe-area-inset-right: env(safe-area-inset-right);
  --safe-area-inset-bottom: env(safe-area-inset-bottom);
  --safe-area-inset-left: env(safe-area-inset-left);
}

The values returned are strings of the inset in pixels with a suffix of “px”. In any of your Phaser scenes, you can include this:

var safeLeft = parseInt(getComputedStyle(document.body).getPropertyValue('--safe-area-inset-left').slice(0,-2));
var safeRight = parseInt(getComputedStyle(document.body).getPropertyValue('--safe-area-inset-right').slice(0,-2));
var safeWidth = this.sys.canvas.width - safeLeft - safeRight;

That is useful if you are working in landscape; change left, right and width to top, bottom and height if you are working in portrait.

This will give you the dimensions of the safe area, so that even though your Phaser canvas invades the non-safe area for you to display backgrounds right to the edge of the screen, you can still confine your display objects inside the safe area. Of course, the CSS variables all return 0px on desktop so they have no effect.

Exit mobile version