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 指南。

瀏覽器相容性

另見