The XRHitTestResult interface of the WebXR Device API contains a single result of a hit test. You can get an array of XRHitTestResult objects for a frame by calling XRFrame.getHitTestResults().
In addition to showing XRHitTestResult within a frame loop, this example demonstrates a few things you must do before requesting this object. While setting up the session, specify "hit-test" as one of the requiredFeatures. Next, call XRSession.requestHitTestSource() with the desired references. (Obtain this by calling XRSession.requestReferenceSpace().) This returns a XRHitTestSource. That you will use in the frame loop to get XRHitTestResult objects.
const xrSession = navigator.xr.requestSession("immersive-ar", {
requiredFeatures: ["local", "hit-test"],
});
let hitTestSource = null;
xrSession
.requestHitTestSource({
space: viewerSpace,
offsetRay: new XRRay({ y: 0.5 }),
})
.then((viewerHitTestSource) => {
hitTestSource = viewerHitTestSource;
});
function onXRFrame(time, xrFrame) {
let hitTestResults = xrFrame.getHitTestResults(hitTestSource);
}
Use getPose() to query the result's pose.
let hitTestResults = xrFrame.getHitTestResults(hitTestSource);
if (hitTestResults.length > 0) {
let pose = hitTestResults[0].getPose(referenceSpace);
}
Once you find intersections on real-world surfaces using hit testing, you can create an XRAnchor to attach a virtual object to that location.
hitTestResult.createAnchor().then(
(anchor) => {
},
(error) => {
console.error(`Could not create anchor: ${error}`);
},
);