XRViewport

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

安全上下文: 此功能仅在安全上下文(HTTPS)中可用,且支持此功能的浏览器数量有限。

WebXR 设备 API 的 XRViewport 接口提供了用于描述渲染 3D 场景的 XRWebGLLayer 中当前视口的尺寸和位置的属性。

实例属性

height 只读

视口的高度(以像素为单位)。

width 只读

视口的宽度(以像素为单位)。

x 只读

从目标图形表面(通常是 XRWebGLLayer)的 origin 到视口左边缘的偏移量(以像素为单位)。

y 只读

从视口的 origin 到视口底部的偏移量;WebGL 的坐标系将 (0, 0) 放置在表面的左下角。

用法说明

当前,唯一可用的表面类型是 XRWebGLLayer。对于其他表面类型,坐标系的精确方向可能会有所不同,但在 WebGL 中,origin (0, 0) 位于表面的左下角。因此,XRViewport 中指定的这些值定义了一个矩形,其左下角位于 (x, y),并向左延伸 width 像素,向上延伸 height 像素。

这些值可以直接传递给 WebGLRenderingContext.viewport() 方法。

js
const xrViewport = xrWebGLLayer.getViewport(xrView);
gl.viewport(xrViewport.x, xrViewport.y, xrViewport.width, xrViewport.height);

示例

此示例使用 requestAnimationFrame() 设置一个动画帧回调。初始设置后,它会遍历查看器姿势中的每个视图,并根据 XRWebGLLayer 配置视口。

js
xrSession.requestAnimationFrame((time, xrFrame) => {
  const viewerPose = xrFrame.getViewerPose(xrReferenceSpace);

  gl.bindFramebuffer(xrWebGLLayer.framebuffer);

  for (const xrView of viewerPose.views) {
    const xrViewport = xrWebGLLayer.getViewport(xrView);
    gl.viewport(
      xrViewport.x,
      xrViewport.y,
      xrViewport.width,
      xrViewport.height,
    );

    // Now we can use WebGL to draw into a viewport matching
    // the viewer's needs
  }
});

规范

规范
WebXR Device API
# xrviewport-interface

浏览器兼容性