<button class="green button" type="button">Start Game</button>
<button class="blue button use-webxr" type="button">
Start Game (VR mode)
</button>WebGLRenderingContext: makeXRCompatible() method
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
const outputCanvas = document.querySelector(".output-canvas");
const gl = outputCanvas.getContext("webgl");
let xrSession = null;
let usingXR = false;
let currentScene = "scene1";
const glStartButton = document.querySelector(".green.button");
const xrStartButton = document.querySelector(".use-webxr");
loadSceneResources(currentScene);
glStartButton.addEventListener("click", handleStartButtonClick);
xrStartButton.addEventListener("click", handleStartButtonClick);
outputCanvas.addEventListener("webglcontextlost", (event) => {
/* The context has been lost but can be restored */
event.canceled = true;
});
/* When the GL context is reconnected, reload the resources for the
current scene. */
outputCanvas.addEventListener("webglcontextrestored", (event) => {
loadSceneResources(currentScene);
});
async function onStartedXRSession(xrSession) {
try {
await gl.makeXRCompatible();
} catch (err) {
switch (err) {
case AbortError:
showSimpleMessageBox(
"Unable to transfer the game to your XR headset.",
"Cancel",
);
break;
case InvalidStateError:
showSimpleMessageBox(
"You don't appear to have a compatible XR headset available.",
"Cancel",
);
break;
default:
handleFatalError(err);
break;
}
xrSession.end();
}
}
async function handleStartButtonClick(event) {
if (event.target.classList.contains("use-webxr") && navigator.xr) {
try {
xrSession = await navigator.xr.requestSession("immersive-vr");
usingXR = true;
} catch (err) {
xrSession = NULL;
usingXR = false;
}
}
startGame();
}
function startGame() {
currentScene = "scene1";
loadSceneResources(currentScene);
/* and so on */
}