You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何传入`XRSession.requestAnimationFrame()`的回调未被调用?

问题原因与解决方案

核心问题是你的代码缺少了XR会话与渲染目标绑定的关键步骤——WebXR的沉浸式会话必须关联一个有效的渲染层(比如XRWebGLLayer),否则浏览器不会触发动画帧回调,因为它不知道要把渲染结果输出到哪里。

哪怕你不需要实际渲染任何内容,也必须完成这个绑定流程才能让动画循环启动。

修改后的代码示例

let session;

const dummyRenderLoop = (time, frame) => {
    if (!session) 
      return;

    console.log("Render callback");
    
    // Continue loop
    session.requestAnimationFrame(dummyRenderLoop);
}

window.addEventListener("load", async () => {
    if (!await navigator.xr.isSessionSupported("immersive-vr")) 
      return;
    
    // Obtain a WebXR session
    session = await navigator.xr.requestSession("immersive-vr");
    if (!session) 
      return;
    
    // ---------- 新增关键代码 ----------
    // 创建canvas并获取兼容XR的WebGL上下文
    const canvas = document.createElement('canvas');
    document.body.appendChild(canvas);
    const gl = canvas.getContext('webgl', { xrCompatible: true });
    // 将会话与WebGL渲染层绑定
    session.baseLayer = new XRWebGLLayer(session, gl);
    // ----------------------------------
    
    // Session creation succeeded
    console.log("Have an XR session");
    
    session.onend = () => {
      console.log("End session");
      session = undefined;
    };
    
    // Initiate animation loop
    session.requestAnimationFrame(dummyRenderLoop);
});

关键说明

  • 必须创建XRWebGLLayer并赋值给session.baseLayer,这是浏览器触发动画帧回调的前置条件
  • xrCompatible: true是WebGL上下文的必要配置,确保它能支持XR渲染
  • 即使你不需要在页面显示canvas,只要完成绑定流程,动画回调就会正常触发

内容的提问来源于stack exchange,提问作者user19642323

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 10:33:23