The XRSession
method requestAnimationFrame()
, much like the Window
method of the same name, schedules a callback to be executed the next time the browser is ready to paint the session's virtual environment to the XR display. The specified callback is executed once before the next repaint; if you wish for it to be executed for the following repaint, you must call requestAnimationFrame()
again. This can be done from within the callback itself.
The callback takes two parameters as inputs: an XRFrame
describing the state of all tracked objects for the session, and a timestamp you can use to compute any animation updates needed.
You can cancel a previously scheduled animation by calling cancelAnimationFrame()
.
Note: Despite the obvious similarities between these methods and the global requestAnimationFrame()
function provided by the Window
interface, you must not treat these as interchangeable. There is no guarantee that the latter will work at all while an immersive XR session is underway.
requestAnimationFrame(animationFrameCallback)
An integer value which serves as a unique, non-zero ID or handle you may pass to cancelAnimationFrame()
if you need to remove the pending animation frame request.
The following example requests XRSession
with "inline" mode so that it can be displayed in an HTML element (without the need for a separate AR or VR device).
Note: A real application should check that the device and the User Agent support WebXR API at all and then that they both support the desired session type via XRSystem.isSessionSupported()
.
const XR = navigator.xr;
XR.requestSession("inline").then((xrSession) => {
xrSession.requestAnimationFrame((time, xrFrame) => {
const viewer = xrFrame.getViewerPose(xrReferenceSpace);
gl.bindFramebuffer(xrWebGLLayer.framebuffer);
for (const xrView of viewer.views) {
const xrViewport = xrWebGLLayer.getViewport(xrView);
gl.viewport(
xrViewport.x,
xrViewport.y,
xrViewport.width,
xrViewport.height,
);
}
});
});
The following example was taken directly from the spec draft. This example demonstrates a design pattern that ensures seamless transition between non-immersive animations created via Window.requestAnimationFrame
and immersive XR animations.
let xrSession = null;
function onWindowAnimationFrame(time) {
window.requestAnimationFrame(onWindowAnimationFrame);
if (!xrSession) {
renderFrame(time, null);
}
}
window.requestAnimationFrame(onWindowAnimationFrame);
function onXRAnimationFrame(time, xrFrame) {
xrSession.requestAnimationFrame(onXRAnimationFrame);
renderFrame(time, xrFrame);
}
function renderFrame(time, xrFrame) {
}
function startXRSession() {
navigator.xr.requestSession("immersive-vr").then((session) => {
xrSession = session;
xrSession.addEventListener("end", onXRSessionEnded);
xrSession.requestAnimationFrame(onXRAnimationFrame);
});
}
function onXRSessionEnded() {
xrSession = null;
}