VR Support with Three.js WebXR
Implement VR support in a Three.js application using the WebXR API to allow users to experience the scene in virtual reality headsets.
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Set up the WebXR manager
renderer.xr.enabled = true;
const button = new VRButton.createButton(renderer);
document.body.appendChild(button);
// Add objects to the scene
camera.position.set(0, 1.6, 0);
const cubeGeometry = new THREE.BoxGeometry(0.2, 0.2, 0.2);
const cubeMaterial = new THREE.MeshNormalMaterial();
const cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
scene.add(cube);
function animate() {
renderer.setAnimationLoop(function () {
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
});
}
animate();
Basic Three.js WebXR setup. A scene, camera, and WebGL renderer are created, then a button to allow entering VR is added. A cube is placed into the scene, and an animation loop with a built-in WebXR support function is set for rendering, which rotates the cube.