Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. WebGLRenderingContext
  4. makeXRCompatible()

WebGLRenderingContext: makeXRCompatible() method

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

Note: This feature is available inWeb Workers.

TheWebGLRenderingContext methodmakeXRCompatible() ensures that the rendering contextdescribed by theWebGLRenderingContext is ready to render the scene for theimmersiveWebXR device on which itwill be displayed. If necessary, theWebGLlayer may reconfigure the context to be ready to render to a different device than itoriginally was.

This is useful if you have an application which can start out being presented on astandard 2D display but can then be transitioned to a 3D immersion system.

Syntax

js
makeXRCompatible()

Parameters

None.

Return value

APromisewhich successfully resolves once the WebGL context is ready to be used for renderingWebXR content.

Exceptions

This method doesn't throw traditional exceptions; instead, the promise rejects with oneof the following errors as the value passed into the rejection handler:

AbortErrorDOMException

Returned if switching the context over to the WebXR-compatible context failed.

InvalidStateErrorDOMException

Returned if the WebGL context has been lost or there is no available WebXR device.

Usage notes

BecausemakeXRCompatible() may involve replacing the underlying WebGLcontext with a new one that uses the new rendering hardware, the existing contents ofthe context may be lost and, therefore, would need to be re-rendered. This is why thewebglcontextlostandwebglcontextrestoredevents are used: the first gives you the opportunity to discard anything you won't needanymore, while the second gives you the opportunity to load resources and prepare torender the scene in its new context.

While this method is available through theWebGLRenderingContextinterface, it's actually defined by theWebXR Device API rather than by WebGL.

Examples

This example demonstrates code logic you might find in a game that starts up usingWebGL to display menus and other UI, and uses WebGL to render gameplay, but has a buttonon its main menu that offers an option to start the game in WebXR mode.

HTML

The HTML for the buttons looks like this:

html
<button type="button">Start Game</button><button type="button">  Start Game (VR mode)</button>

The first button starts the game, continuing to present the game onscreen as usual. Thesecond button will be used to start the game inimmersive-vr mode. Note theinclusion of ause-webxr class on the VR mode button. This is important,which we'll explore shortly.

JavaScript

The code that handles starting up graphics, switching to VR mode, and so forth lookslike this:

js
const outputCanvas = document.querySelector(".output-canvas");const gl = outputCanvas.getContext("webgl");let xrSession = null;let usingXR = false;let currentScene = "scene1";let glStartButton;let xrStartButton;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 */}

This works by having two buttons, one which starts the game normally and the otherwhich starts the game in VR mode. These both use thehandleStartButtonClick() function as their event handler. The functiondetermines that the button clicked was the one requestingimmersive-vr modeby checking to see if the button has theuse-webxr class on it. If thebutton clicked by the user has that class (and we've confirmed that WebXR is availableby ensuring that thenavigator.xr property exists), we userequestSession() to request a new WebXRsession and set theusingXR flag totrue.

If the other button was clicked, we ensure thatxrSession isNULL and clearusingXR tofalse.

Then thestartGame() function is called to trigger the beginning ofgameplay.

Handlers are provided for bothwebglcontextlostandwebglcontextrestored;in the first case, we make sure we're aware that the state can be recovered, while inthe latter we actually reload the scene to ensure we have the correct resources for thecurrent screen or headset configuration.

Specifications

Specification
WebXR Device API
# dom-webglrenderingcontextbase-makexrcompatible

Browser compatibility

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp