VRDisplay: requestPresent() 方法

已弃用:此特性不再推荐。虽然某些浏览器可能仍然支持它,但它可能已经从相关的网络标准中删除,可能正在删除过程中,或者可能仅为兼容性目的而保留。请避免使用它,如果可能,请更新现有代码;请参阅本页底部的兼容性表格以指导您的决策。请注意,此特性可能随时停止工作。

非标准:此特性未标准化。我们不建议在生产环境中使用非标准特性,因为它们浏览器支持有限,并且可能会更改或被移除。但是,在没有标准选项的特定情况下,它们可以是合适的替代方案。

VRDisplay 接口的 requestPresent() 方法用于启动 VRDisplay 来呈现一个场景。

注意:此方法是旧版 WebVR API 的一部分。它已被 WebXR Device API 取代。

语法

js
requestPresent(layers)

参数

layers

一个包含 VRLayerInit 对象的数组,表示您希望呈现的场景。目前,这个数组可以包含 0 到 1 个对象。

返回值

一个在呈现开始后解析的 Promise。关于 Promise 的履行或拒绝,有一些规则。

  • 如果 VRDisplayCapabilities.canPresent 为 false,或者 VRLayer 数组包含的层数超过 VRDisplayCapabilities.maxLayers,则 Promise 将被拒绝。
  • 如果在调用 requestPresent()VRDisplay 已经在呈现,那么 VRDisplay 将会更新当前呈现的 VRLayer 数组。
  • 如果在 VRDisplay 正在呈现时调用 requestPresent() 被拒绝,它将结束其呈现。
  • 如果 requestPresent() 在非用户交互事件(engagement gesture)中被调用,则 Promise 将被拒绝,除非 VRDisplay 已经在呈现。此用户交互事件也足以允许 requestPointerLock() 调用,直到呈现结束。

示例

js
if (navigator.getVRDisplays) {
  console.log("WebVR 1.1 supported");
  // Then get the displays attached to the computer
  navigator.getVRDisplays().then((displays) => {
    // If a display is available, use it to present the scene
    if (displays.length > 0) {
      vrDisplay = displays[0];
      console.log("Display found");
      // Starting the presentation when the button is clicked: It can only be called in response to a user gesture
      btn.addEventListener("click", () => {
        if (btn.textContent === "Start VR display") {
          vrDisplay.requestPresent([{ source: canvas }]).then(() => {
            console.log("Presenting to WebVR display");

            // Set the canvas size to the size of the vrDisplay viewport

            const leftEye = vrDisplay.getEyeParameters("left");
            const rightEye = vrDisplay.getEyeParameters("right");

            canvas.width =
              Math.max(leftEye.renderWidth, rightEye.renderWidth) * 2;
            canvas.height = Math.max(
              leftEye.renderHeight,
              rightEye.renderHeight,
            );

            // stop the normal presentation, and start the vr presentation
            window.cancelAnimationFrame(normalSceneFrame);
            drawVRScene();

            btn.textContent = "Exit VR display";
          });
        } else {
          vrDisplay.exitPresent();
          console.log("Stopped presenting to WebVR display");

          btn.textContent = "Start VR display";

          // Stop the VR presentation, and start the normal presentation
          vrDisplay.cancelAnimationFrame(vrSceneFrame);
          drawScene();
        }
      });
    }
  });
}

注意:您可以在 raw-webgl-example 中查看此完整代码。

规范

此方法是旧版 WebVR API 的一部分,已被 WebXR Device API 取代。它不再是标准化的方向。

在所有浏览器都实现新的 WebXR API 之前,建议依靠 A-FrameBabylon.jsThree.js 等框架,或 polyfill 来开发可在所有浏览器上运行的 WebXR 应用程序。有关更多信息,请阅读 Meta 的从 WebVR 移植到 WebXR 指南。

浏览器兼容性

另见