VRDisplay.requestPresent()

Экспериментальная возможность: Это экспериментальная технология
Так как спецификация этой технологии ещё не стабилизировалась, смотрите таблицу совместимости по поводу использования в различных браузерах. Также заметьте, что синтаксис и поведение экспериментальной технологии может измениться в будущих версиях браузеров, вслед за изменениями спецификации.

Метод requestPresent() объекта реализующего интерфейс VRDisplay (en-US) отвечает за начало отображения сцены на VR устройстве, которое представлено этим объектом.

Синтаксис

js
vrDisplayInstance.requestPresent(layers).then(function () {
  //Действия после начала отображения сцены
});

Параметры

layers

Массив объектов типа VRLayerInit (en-US), представляющих собой сцену, которую вы хотите отобразить. На данный момент может быть минимум 0 элементов, максимум - 1.

Возвращаемое значение

Объект типа Promise, переходящий в состояние "выполнено" в момент начала отображения сцены. Существует ряд правил, касающийся перехода Promise в состояние "выполнено" и в состояние "отклонено":

  • Если VRDisplayCapabilities.canPresent (en-US) ложно или если массив объектов VRLayer содержит более чем VRDisplayCapabilities.maxLayers (en-US) слоёв, произойдёт переход в состояние "отклонено".
  • Если объект VRDisplay (en-US) уже отображает сцену, то вызов его метода requestPresent() обновит массив отображаемых VRLayer объектов.
  • Если объект VRDisplay уже отображает сцену, а вызов метода requestPresent() приведёт к возврату Promise в состоянии "отклонено", то отображение сцены прекратится.
  • If requestPresent() is called outside of an engagement gesture the promise will be rejected unless the VRDisplay was already presenting. This engagement gesture is also sufficient to allow requestPointerLock() calls until presentation has ended.

Examples

js
if (navigator.getVRDisplays) {
  console.log("WebVR 1.1 supported");
  // Then get the displays attached to the computer
  navigator.getVRDisplays().then(function (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", function () {
        if (btn.textContent === "Start VR display") {
          vrDisplay.requestPresent([{ source: canvas }]).then(function () {
            console.log("Presenting to WebVR display");

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

            var leftEye = vrDisplay.getEyeParameters("left");
            var 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();
        }
      });
    }
  });
}

Примечание: You can see this complete code at raw-webgl-example.

Specifications

No specification found

No specification data found for api.VRDisplay.requestPresent.
Check for problems with this page or contribute a missing spec_url to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

Совместимость с браузерами

BCD tables only load in the browser

See also