为何传入`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
相关产品推荐
相关产品推荐

