使用 WebXR 建立沉浸式 AR 工作階段

本頁面將逐步引導您使用 WebXR 建立簡單的沉浸式 AR 應用程式。

您需要與 WebXR 相容的開發環境才能開始使用。

建立 HTML 網頁

WebXR 需要使用者互動才能啟動工作階段。建立呼叫 activateXR() 的按鈕。頁面載入後,使用者只要按下這個按鈕,即可啟動 AR 體驗。

建立名為 index.html 的新檔案,並加入以下 HTML 程式碼:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <title>Hello WebXR!</title>

  <!-- three.js -->
  <script src="https://unpkg.com/three@0.126.0/build/three.js"></script>
</head>
<body>

<!-- Starting an immersive WebXR session requires user interaction.
    We start this one with a simple button. -->
<button onclick="activateXR()">Start Hello WebXR</button>
<script>
async function activateXR() {
  // Add a canvas element and initialize a WebGL context that is compatible with WebXR.
  const canvas = document.createElement("canvas");
  document.body.appendChild(canvas);
  const gl = canvas.getContext("webgl", {xrCompatible: true});

  // To be continued in upcoming steps.
}
</script>
</body>
</html>

初始化 3.js

按下「開始」按鈕並不會發生太多資料。如要設定 3D 環境,您可以使用算繪程式庫顯示場景。

在本例中,您將使用提供 WebGL 轉譯器的 JavaScript 3D 算繪程式庫 three.jsThree.js 可處理算繪、相機和場景圖,方便你在網路上顯示 3D 內容。

建立場景

3D 環境通常都是模擬場景。建立包含 AR 元素的 THREE.Scene。下方程式碼可讓您在 AR 中看到彩色方塊。

請在 activateXR() 函式底部新增以下程式碼:

const scene = new THREE.Scene();

// The cube will have a different color on each side.
const materials = [
  new THREE.MeshBasicMaterial({color: 0xff0000}),
  new THREE.MeshBasicMaterial({color: 0x0000ff}),
  new THREE.MeshBasicMaterial({color: 0x00ff00}),
  new THREE.MeshBasicMaterial({color: 0xff00ff}),
  new THREE.MeshBasicMaterial({color: 0x00ffff}),
  new THREE.MeshBasicMaterial({color: 0xffff00})
];

// Create the cube and add it to the demo scene.
const cube = new THREE.Mesh(new THREE.BoxBufferGeometry(0.2, 0.2, 0.2), materials);
cube.position.set(1, 1, 1);
scene.add(cube);

使用 Three.js 設定轉譯功能

如果想用 AR 檢視這個場景,需使用轉譯器相機。 轉譯器會使用 WebGL 在螢幕上繪製場景。相機描述了檢視場景的可視區域。

請在 activateXR() 函式底部新增以下程式碼:

// Set up the WebGLRenderer, which handles rendering to the session's base layer.
const renderer = new THREE.WebGLRenderer({
  alpha: true,
  preserveDrawingBuffer: true,
  canvas: canvas,
  context: gl
});
renderer.autoClear = false;

// The API directly updates the camera matrices.
// Disable matrix auto updates so three.js doesn't attempt
// to handle the matrices independently.
const camera = new THREE.PerspectiveCamera();
camera.matrixAutoUpdate = false;

建立 XRSession

WebXR 的進入點是透過 XRSystem.requestSession()。使用 immersive-ar 模式,即可在實際環境中查看轉譯後的內容。

XRReferenceSpace 說明瞭虛擬世界中物件使用的座標系統。'local' 模式最適合用於 AR 體驗,其參照空間來源位於檢視器和穩定追蹤附近。

如要建立 XRSessionXRReferenceSpace,請在 activateXR() 函式底部新增以下程式碼:

// Initialize a WebXR session using "immersive-ar".
const session = await navigator.xr.requestSession("immersive-ar");
session.updateRenderState({
  baseLayer: new XRWebGLLayer(session, gl)
});

// A 'local' reference space has a native origin that is located
// near the viewer's position at the time the session was created.
const referenceSpace = await session.requestReferenceSpace('local');

轉譯場景

您現在可以算繪場景。XRSession.requestAnimationFrame() 會排定在瀏覽器準備繪製影格時執行的回呼。

在動畫影格回呼期間,呼叫 XRFrame.getViewerPose() 即可取得相對於本機座標空間的檢視器姿勢。這可用於更新場景鏡頭,在轉譯器透過新版相機繪製場景前,變更使用者查看虛擬世界的方式。

請在 activateXR() 函式底部新增以下程式碼:

// Create a render loop that allows us to draw on the AR view.
const onXRFrame = (time, frame) => {
  // Queue up the next draw request.
  session.requestAnimationFrame(onXRFrame);

  // Bind the graphics framebuffer to the baseLayer's framebuffer
  gl.bindFramebuffer(gl.FRAMEBUFFER, session.renderState.baseLayer.framebuffer)

  // Retrieve the pose of the device.
  // XRFrame.getViewerPose can return null while the session attempts to establish tracking.
  const pose = frame.getViewerPose(referenceSpace);
  if (pose) {
    // In mobile AR, we only have one view.
    const view = pose.views[0];

    const viewport = session.renderState.baseLayer.getViewport(view);
    renderer.setSize(viewport.width, viewport.height)

    // Use the view's transform matrix and projection matrix to configure the THREE.camera.
    camera.matrix.fromArray(view.transform.matrix)
    camera.projectionMatrix.fromArray(view.projectionMatrix);
    camera.updateMatrixWorld(true);

    // Render the scene with THREE.WebGLRenderer.
    renderer.render(scene, camera)
  }
}
session.requestAnimationFrame(onXRFrame);

執行 Hello WebXR

前往裝置上的 WebXR 檔案。這樣應該就能從各個角度看到彩色方塊。

新增命中測試

與 AR 世界互動的常見方法是透過「命中測試」,找出射線與真實世界幾何之間的交集。在 Hello WebXR 中,您將使用命中測試在虛擬世界中放置向日葵。

移除示範方塊

移除未亮起的方塊,並換成含有打光效果的場景:

const scene = new THREE.Scene();

const directionalLight = new THREE.DirectionalLight(0xffffff, 0.3);
directionalLight.position.set(10, 15, 10);
scene.add(directionalLight);

使用「hit-test」功能

如要初始化命中測試功能,請使用 hit-test 功能要求工作階段。找出先前的 requestSession() 片段,並新增 hit-test

const session = await navigator.xr.requestSession("immersive-ar", {requiredFeatures: ['hit-test']});

新增模型載入器

這個場景目前只包含彩色方塊。為了營造更有趣的體驗,請新增模型載入器,以便載入 GLTF 模型

在文件的 <head> 標記中新增 three.js' GLTFLoader

<!-- three.js -->
<script src="https://unpkg.com/three@0.126.0/build/three.js"></script>

<script src="https://unpkg.com/three@0.126.0/examples/js/loaders/GLTFLoader.js"></script>

載入 GLTF 模型

使用上一個步驟的模型載入器,從網路載入指定目標邏輯和向日葵。

onXRFrame 上方加入這段程式碼:

const loader = new THREE.GLTFLoader();
let reticle;
loader.load("https://immersive-web.github.io/webxr-samples/media/gltf/reticle/reticle.gltf", function(gltf) {
  reticle = gltf.scene;
  reticle.visible = false;
  scene.add(reticle);
})

let flower;
loader.load("https://immersive-web.github.io/webxr-samples/media/gltf/sunflower/sunflower.gltf", function(gltf) {
  flower = gltf.scene;
});

// Create a render loop that allows us to draw on the AR view.
const onXRFrame = (time, frame) => {

建立命中測試來源

如要計算與真實物件的交集,請使用 XRSession.requestHitTestSource() 建立 XRHitTestSource。用於命中測試的光線具有 viewer 參照空間做為來源,表示命中測試是從可視區域的中心完成。

若要建立命中測試來源,請在建立 local 參照空間後加入下列程式碼:

// A 'local' reference space has a native origin that is located
// near the viewer's position at the time the session was created.
const referenceSpace = await session.requestReferenceSpace('local');

// Create another XRReferenceSpace that has the viewer as the origin.
const viewerSpace = await session.requestReferenceSpace('viewer');
// Perform hit testing using the viewer as origin.
const hitTestSource = await session.requestHitTestSource({ space: viewerSpace });

繪製指定目標標本

如要清楚指出太陽花在哪裡,請在場景中加入指定目標標本。這個標線看起來會固定在現實世界的表面上,象徵向日葵的固定位置。

XRFrame.getHitTestResults 會傳回 XRHitTestResult 的陣列,並公開包含實際幾何圖形的交集。請使用這些交集,為每個頁框定位指定目標。

camera.projectionMatrix.fromArray(view.projectionMatrix);
camera.updateMatrixWorld(true);

const hitTestResults = frame.getHitTestResults(hitTestSource);
if (hitTestResults.length > 0 && reticle) {
  const hitPose = hitTestResults[0].getPose(referenceSpace);
  reticle.visible = true;
  reticle.position.set(hitPose.transform.position.x, hitPose.transform.position.y, hitPose.transform.position.z)
  reticle.updateMatrixWorld(true);
}

輕觸時新增互動

當使用者完成主要動作時,XRSession 會收到 select 事件。在 AR 工作階段中,這代表輕觸畫面。

在初始化期間新增下列程式碼,讓使用者輕觸螢幕時,就能顯示新的向日葵:

let flower;
loader.load("https://immersive-web.github.io/webxr-samples/media/gltf/sunflower/sunflower.gltf", function(gltf) {
  flower = gltf.scene;
});

session.addEventListener("select", (event) => {
  if (flower) {
    const clone = flower.clone();
    clone.position.copy(reticle.position);
    scene.add(clone);
  }
});

測試命中測試

使用行動裝置前往該網頁。WebXR 建立對環境的理解後,邏輯應該出現在現實世界的表面上。輕觸螢幕放置向日葵,從頭到尾都可以查看。

後續步驟