DOM Overlay
On a phone, an AR session takes over the whole screen, so the page's HTML disappears with it. DOM Overlay keeps one element of the page on screen during the session, over the AR view, so you can build the interface with HTML and CSS: buttons, instructions, a menu.
Only Chrome on Android phones offers DOM Overlay. Headsets have no flat screen to put it on, so use UI in the scene there. See Platforms.
Setting Up
Choose the element to show, the overlay's root, and set it before the session starts. An AR session asks for DOM Overlay whenever a root is set:
<div id="overlay">
<button id="exit">Exit AR</button>
<p id="hint">Move your phone slowly to find the floor</p>
</div>
const overlay = document.getElementById('overlay');
app.xr.domOverlay.root = overlay;
document.getElementById('exit').addEventListener('click', () => {
app.xr.end();
});
camera.camera.startXr(XRTYPE_AR, XRSPACE_LOCALFLOOR);
During the session, the browser shows the root and everything in it full screen, over the AR view, and hides the rest of the page. Style the root to fill the screen, with a transparent background so that the AR view shows through it. The root can only be changed between sessions.
app.xr.domOverlay.supported is true when the browser implements DOM Overlay, and available is true while a session has it. state says how the browser shows it: 'screen' on a phone, over the whole screen. The specification also allows 'floating' and 'head-locked', for overlays in a headset, which no browser offers.
Taps on the Overlay
A tap on the overlay is also a tap on the AR view, so it fires select in the scene, and could place an object behind the button that the user meant to press. To stop that, cancel the beforexrselect event that the browser fires on the overlay's elements before such a select. It bubbles, so one listener on the root covers its children. This cancels taps on every element of the overlay except the root, so that taps on the empty part of the screen still reach the scene:
overlay.addEventListener('beforexrselect', (evt) => {
if (evt.target !== overlay) {
evt.preventDefault();
}
});
See Also
- UI in XR - Interfaces in the scene, for headsets and phones
- WebXR AR: DOM Overlay - A tutorial with an overlay in the Editor
- XrDomOverlay - API reference