Three.js WebXR Hit Test & Anchors (AR Placement)

Place virtual objects on real surfaces with WebXR in Three.js, using a hit-test source for the reticle and anchors that stay locked to the world, with a desktop simulation that raycasts a room and adds tracking drift to show why anchors matter.

Key topics: webxr hit test, xr anchors, ar placement, augmented reality three.js, reticle, immersive-ar

What this code does

- Hit Test: in AR, `session.requestHitTestSource({ space: viewer })` returns, each frame, poses where a ray from the device centre meets real geometry, which drives the reticle.
- Placement: on select, an object is spawned at the hit pose, and the reticle's matrix carries the surface normal so items sit flat on tables and walls.
- Anchors: `hitResult.createAnchor()` gives an XRAnchor whose `anchorSpace` the runtime keeps re-localising, so anchored content stays put as tracking improves.
- Drift Simulation: on desktop the session frame slides and rotates slowly relative to the room; free objects ride the drifting frame while anchored ones stay glued to real surfaces.
- Simulated Hit Test: the mouse ray is cast against the ground-truth room meshes (floor, table, shelf, walls).
- Controls: object, create anchors, drift, auto demo and clear; Enter AR requests hit-test plus optional anchors and dom-overlay.

Continue Learning

JavaScript Implementation

ES6+
// WebXR hit test + anchors
const session = await navigator.xr.requestSession('immersive-ar', { requiredFeatures: ['hit-test'], optionalFeatures: ['anchors'] })
const hitSource = await session.requestHitTestSource({ space: await session.requestReferenceSpace('viewer') })
renderer.setAnimationLoop((time, frame) => {
  const hit = frame.getHitTestResults(hitSource)[0]
  if (hit) reticle.matrix.fromArray(hit.getPose(refSpace).transform.matrix)
  for (const { anchor, mesh } of anchored) {
    const pose = frame.getPose(anchor.anchorSpace, refSpace)   // re-localised every frame
    if (pose) mesh.matrix.fromArray(pose.transform.matrix)
  }
  renderer.render(scene, camera)
})
controller.addEventListener('select', async () => anchored.push({ anchor: await hit.createAnchor(), mesh: spawn() }))