Web Setup Guide
Web Setup Guide
ViroReact runs in the browser through react-native-web and a WebAssembly build of the same C++ renderer, shipped as the optional peer @reactvision/viro-web-renderer.
Available in ViroReact 3.0.0 and later. For ViroReact 3.0.2, use
@reactvision/viro-web-renderer1.0.1+ (the peer range asks for it) — heap growth, tap fixes, and pose hold live in that renderer build. Use ViroReact 3.0.3+ to bundle with Vite or webpack (3.0.2'sdist/shipped raw JSX). ViroReact 3.2.3 needs@reactvision/viro-web-renderer1.3.0 (the peer range is^1.3.0). ViroReact 3.2.2 uses renderer 1.2.0.
Requirements
| Mode | Needs |
|---|---|
| 3D scenes | WebGL2 |
| AR | WebGL2 and HTTPS and a device with an IMU |
Camera, 6-DoF pose, plane detection, and hit test come from ReactVision's visual-inertial tracker bundled with the web renderer — no ARCore/ARKit in the browser.
Install
npm install @reactvision/react-viro @reactvision/viro-web-renderer@^1.3.0 react-native-web
3.2.2+: copy the renderer's whole wasm/ folder wherever you serve its files from. From 3.2.2 it carries the Roboto faces that styled ViroText loads on demand, beside the .wasm and .data files. ViroReact 3.2.3 needs renderer 1.3.0; 3.2.2 uses 1.2.0; 3.2.0 and 3.2.1 use 1.1.1.
Use the same scene components you already know (ViroScene, ViroBox, …). Wire your bundler for react-native-web as you would for any React Native Web app; the Viro package resolves web stubs for native-only modules.
Bundlers: Vite and webpack (3.0.3+)
From 3.0.3 the published package bundles directly with Vite and webpack. You don't need to transpile node_modules.
dist/is compiled with the automatic JSX runtime ("jsx": "react-jsx"). 3.0.2 left raw JSX in 105 of 242dist/files, which Vite and webpack do not transform, so 3.0.2 could not be bundled for the web.- Asset sources resolve on the web without React Native's
AssetSourceResolver, which react-native-web lacks. Sources pass through as the web components take them, so calls likeViroARTrackingTargets.createTargetsno longer throw on the first asset. - Keep your usual react-native-web setup (alias
react-native→react-native-web).
What works / what does not
- Works: 3D scenes, AR tracking (pose / planes / hit test), most geometry and materials, Editor scenes via
StudioSceneNavigator(web). 3.2.0+: physics and collisions, scene navigation inViroARSceneNavigator, and previewing an AR scene withvirtualCamera. 3.2.2+: pinch, rotate and fuse, drag in live AR, node ref reads, styled text, material effects, camera reads, AR hit tests,Viro3DSceneNavigatornavigation and sound that mixes with video. 3.2.3+: scene-wide events andViroController, portals, per-face materials, animated images, full particle and physics support, post-process effects, capture on every navigator, and AR plane detection on by default. See In 3.2.3. - Does not: Co-location / VPS cloud anchors (a browser cannot align with a device's scan —
FRAME_KIND_UNSUPPORTED), AR session recording (the IMU and camera-feed recording, which is distinct fromtakeScreenshotand video recording), Quest/visionOS-only input (e.g.onGaze), and occlusion in Editor scenes.
Native-only components without a .web implementation stub out safely rather than crashing the import barrel (fixed in 2.58.x).
Web AR options (3.0.2+)
Pass capture/tuning options through arOptions on ViroARSceneNavigator / StudioSceneNavigator (web):
| Option | Purpose |
|---|---|
feedWidth / feedHeight | Camera feed dimensions |
poseSmoothing | Smooth pose through brief tracking dropouts (web AR also holds the last pose through a dropout) |
hideContentWhenLost | 3.1.0+ (viro-web-renderer 1.1.0). The renderer hides the scene's content while tracking is lost. Set hideContentWhenLost: false to keep it visible. |
Denied motion permission (or no motion events) is reported via onMotionUnavailable on both navigators, with an on-screen message.
In 3.2.3 (viro-web-renderer 1.3.0)
3.2.3 closes most of the remaining gaps from the web-vs-native parity review. Everything here is web platform support: it is new on web and works the same way on iOS and Android already. Update @reactvision/viro-web-renderer to 1.3.0 (the peer range is now ^1.3.0) and copy its whole wasm/ folder. Against 1.2.0 at runtime, the new features stay off and a one-time warning names what is missing.
Navigators
projectandunprojectwork onViroARSceneNavigator,Viro3DSceneNavigatorandViroVRSceneNavigator, with the same return shapes as native ({ screenPosition }and{ position }). They need the camera's pose, so they throw before an AR session starts. See ViroARSceneNavigator.- Refs: the 3D and VR navigators expose
sceneNavigatoron the ref, and the AR navigator exposesarSceneNavigatoras well assceneNavigator. takeScreenshot,startVideoRecordingandstopVideoRecordingwork on all three. The result shape is the same as native (success,url,errorCode).urlis an object URL you may revoke.saveToCameraRolldownloads the file, because the web has no camera roll. Video carries no audio: native records the microphone, which a browser would have to ask for separately. Editor scenes'TAKE_PHOTOandRECORD_VIDEOfunctions use this capture.recenterTrackingis present but does nothing, because there is no headset to re-zero.ViroVRSceneNavigatorrenders in mono, as a phone shows the scene withvrModeEnabled={false}.
Events
- Scene-level
onClick,onClickState,onHover,onPinch,onRotateandonFusefire when the event is not captured on a node. A tap on empty space reports position[], as native does. onTransformUpdate,ignoreEventHandling,rotationPivot,scalePivotandhighAccuracyEventswork on nodes. See ViroNode.ViroControllerreports scene-wide clicks, pinches, rotates, fuses and drags.onTouch,onScroll,onSwipeandonControllerStatusstill warn: those come from a hand controller, which the web does not have. See ViroController.
Animation
- Chains, sequences, parallels and aliases survive
registerAnimations. run={false}pauses andrun={true}resumes a declarative animation.onFinishfires at the end of every pass, including a looping animation.colorandmaterialanimate. See Animation.
Materials, geometry and media
- A model's
materialsreach it, amaterialsarray applies per face or submesh, andViroGeometrykeeps its submeshes. arShadowReceiverworks onViroQuadandViroPolygon. Primitive options work:ViroQuaduvCoordinates,ViroSpheresegments andfacesOutward,ViroPolygonholes and UVs. Primitives rebuild when their size changes.ViroAnimatedImageanimates throughImageDecoder. Images and videos takestereoModeandplaceholderSource.ViroSkyBoxtakescolor, andViro360ImagetakesisHdr.- Media supports
seekToTime,onBufferStart,onBufferEndandonUpdateTime.ViroSound.preloadSounds/unloadSounds,StreamingAudioManager(pushed PCM through Web Audio) andViroImage.evictFromCachework. - A
.gltfwith external.binor image files loads. They are fetched beside the model or fromresourcesand inlined; a missing file fails that model throughonErrorinstead of aborting the page.
Portals, physics, particles and lights
- Each portal gets its own background, and
onPortalEnter/onPortalExitfire. See ViroPortalScene. - Physics. Hidden bodies leave the simulation, empty Compound shapes build from the children,
applyImpulsewith an offset adds torque,velocityis constant, held force and torque work, andfindCollisionsWithRayAsync,findCollisionsWithShapeAsyncanddrawBoundswork. In 3.2.0drawBoundsand an impulse offset only warned. See Physics. - Particle emitters take every native prop and update while running. See ViroParticleEmitter.
shadowOrthographicPositionplaces a directional light. See ViroDirectionalLight.postProcessEffectsonViroSceneandViroARSceneapply the named effects (grayscale,sepia, and the others in Post-Process Effects). Unknown names are skipped with a warning.
AR
- Plane detection is on by default, as on native. Set
arOptions.detectPlanestofalseto turn it off. Before 3.2.3, omitting it left detection off. - Tracking reasons,
onTrackingInitializedandonPlatformUpdatefire.anchorDetectionTypesfilters planes. A plane can report classification and vertices when the feed has them, andpauseUpdatesworks. See ViroARPlane. onCameraARHitTestworks, including hit tests on a virtual camera's planes.- The camera feed is cropped to fill the screen instead of stretched, and the projection uses the same crop, so content stays where it belongs near the edges.
Permissions and cameras
checkPermissionsandrequestRequiredPermissionsanswercamera,microphoneandlocation. They used to resolve{}, so an app gating AR onresult.cameranever opened it.storageis always false: the web has no camera roll. Asking for the microphone after aViroSoundworks on Safari. See Permission helpers.ViroOrbitCameralooks at its focal point (its yaw and pitch signs were flipped). Releasing aViroCamerareturns to the default camera, never to an earlier one.- Camera reads and drag work under a perspective
ViroCameraorViroOrbitCamerain a 3D scene. They still cannot under an orthographic projection, or while that camera is the point of view in live AR. In 3.2.2 they could not under a camera component at all.
Editor scenes on web. StudioSceneNavigator wraps scenes in the native error boundary with retry, so a scene that throws no longer replaces the whole page. MANUAL plane detection mounts the plane selector. Proximity runs without an AR session. TAKE_PHOTO and RECORD_VIDEO use the navigator capture. See StudioSceneNavigator.
In 3.2.2 (viro-web-renderer 1.2.0)
3.2.2 brings the web runtime close to native. Everything here is web platform support: it is new on web and works the same way on iOS and Android already. Update @reactvision/viro-web-renderer to 1.2.0 (the peer range is now ^1.2.0) and copy its whole wasm/ folder, which now carries the Roboto faces styled text uses. Against an older renderer at runtime, styled text, material effects, two-finger gestures and node reads fall back with a console warning instead of failing.
Gestures and drag
onPinch,onRotateandonFuse.onPinch(pinchState, scaleFactor, source)andonRotate(rotateState, rotationFactor, source)come from two fingers on a touch screen; the rotation factor is in degrees, counterclockwise, as native reports it.onFusetakes a function or{ callback, timeToFuse }and fires once the centre of the screen has rested on the node fortimeToFusemilliseconds (default 2000).- Drag works in live AR and in the 3D navigators (
ViroSceneNavigatorandViro3DSceneNavigator), not only withvirtualCamera. The node follows the pointer every frame in its parent's space. A press that a second finger cancels ends its drag. In Editor scenes,FixedToPlaneslides along the plane the asset's anchor found.
Node refs
const box = useRef<any>(null);
const t = await box.current.getTransformAsync(); // { position, rotation, scale }, world space, rotation in degrees
const b = await box.current.getBoundingBoxAsync(); // { boundingBox: { minX, maxX, minY, maxY, minZ, maxZ } }
const m = await box.current.getMorphTargets(); // { targets: string[] }
box.current.setNativeProps({ position: [0, 1, -2], opacity: 0.5, visible: true });
getTransformAsyncandgetBoundingBoxAsyncread the last frame.getMorphTargetsanswers on any node on web. On native it is a Viro3DObject method.setNativePropssetsposition,rotation,scale,opacityandvisible, until the props next change them. Any other key warns; pass those as props.
Text and materials
ViroTexttakesstyle.fontWeight("normal","bold", or 100 to 900),style.fontStyle("italic"),extrusionDepthandouterStroke({ type: "Outline" | "DropShadow", width, color }). The web carries Roboto only, as Android'ssans-serif: a family it lacks draws in Roboto at the weight and style you ask for. As on iOS,materialsdress extruded text only. See ViroText.- Materials take
alpha,bloomThreshold,colorWriteMaskandchromaKeyFilteringColor. Analphabelow 1 turns depth writing off unless the material setswritesToDepthBuffer, as on native.materialUniformsandshaderUniformsare set when a material is created. See ViroMaterials.
AR
onAmbientLightUpdateonViroARSceneis estimated from the camera feed about four times a second and smoothed. On web it reports{ intensity, color }, where an intensity of 1000 is a neutrally lit room, as on ARKit and ARCore, andcoloris a hex string. Editor scenes use it to scale their light rig.- Camera reads:
onCameraTransformUpdate,getCameraOrientationAsyncandgetCameraPositionAsyncreport the AR session's camera, thevirtualCamera, or the 3D navigators' default camera. In 3.2.2, with aViroCameraorViroOrbitCameraas the point of view the pose is not known and the call warns or rejects; 3.2.3 adds reads under a perspective camera component in a 3D scene. Before an AR session starts there is no pose yet. - Hit tests return
ViroARHitTestResult:performARHitTestWithPoint,performARHitTestWithRay,performARHitTestWithWorldPoints(origin, destination)andperformARHitTestWithPosition. The web tracker finds planes only, so a hit isExistingPlaneUsingExtentinside a plane's detected rectangle andExistingPlaneon its extension, withhasDepthDatafalse. resetARSession(true, …)restarts the tracker: a new world origin at the camera, and the old planes are gone.resetARSessionwith onlyremoveAnchorsandsetWorldOriginwarn, because the tracker cannot do either.isARSupportedOnDeviceanswers from what the browser offers: a secure context, a camera API and motion events. A desktop browser can pass it and then report missing motion when AR starts.- Cloud anchors report themselves unsupported: the web AR tracker cannot host or resolve them.
Navigation and animation
Viro3DSceneNavigatornavigates:push,pop,popN,jumpandreplacework, andinitialScenetakespassProps. Only the top scene of the stack is mounted. Native keeps the others, but nothing on web can show them while they are covered.arSceneNavigator: AR scenes get the navigator under that name as well assceneNavigator. Methods the web cannot run stay absent rather than stubbed, sonav?.resolveCloudAnchorstill feature-tests.- Animations: a declarative animation's
onStartandonFinishfire, a relative animation ("+=90") starts from where the node is, and model clips honourdelay.
Media and context loss
- Sound mixes with video on iPhone. Sounds play from decoded buffers on one
AudioContext; on iOS WebKit a sound beside a video with sound used to go quiet. The page asks for a playback audio session, so the ring/silent switch does not mute them. - Held-back media plays at the first gesture. Browsers refuse sound until the page has had a tap, click or key press. A refused sound or video now waits for that gesture; a video plays muted meanwhile so its picture runs, and gets its sound at the gesture.
- A lost WebGL context recovers. When the browser gives the context back, the navigators create a new renderer and mount the scene again, so a scene's own state starts over, and live AR shows its Start button again.
Editor scenes on web. StudioSceneNavigator follows the native host's rules for animations, shows ALERT in a dialog over the canvas, fires onSceneChange once a navigation has loaded, and holds a NONE scene's assets until tracking settles. See StudioSceneNavigator.
In 3.2.0 (viro-web-renderer 1.1.1)
-
virtualCameraonViroARSceneNavigator. Renders an AR scene with no camera, session or permission prompt, from a camera the viewer moves: right or middle drag to look around, shift-drag to pan, the wheel or a pinch to zoom, two fingers to orbit. A primary click or a single finger still reaches the scene as a tap. A floor plane is reported toViroARPlaneatfloorY(default -1), so plane content shows. Use it to preview an AR scene where there is nothing to track with, such as a desktop browser. See ViroARSceneNavigator → virtualCamera.<ViroARSceneNavigator initialScene={{ scene: MyARScene }} virtualCamera /> -
Dragging with
virtualCamera.onDragenables it, withdragTypeFixedDistance(the default),FixedDistanceOrigin,FixedToPlane(withdragPlane) orFixedToWorld(the horizontal plane through the grabbed point, since there are no detected surfaces). A dynamic body is held kinematic while dragged and thrown with the pointer's velocity when let go. Dragging under a rotated or scaled parent is not exact yet in 3.2.0, and live web AR has no drag in 3.2.0 (it warns); 3.2.2 adds drag to live AR and the 3D navigators. -
Scene navigation in
ViroARSceneNavigator.push,replace,jump,popandpopNwork, with the native navigator's tag semantics. They used to warn and do nothing. -
Physics. A scene switches the physics world on when it mounts, so a
physicsBodysimulates;physicsWorld.gravitysets the gravity (default -9.81) anddrawBoundswarns in 3.2.0 (3.2.3 addsdrawBounds, offset torque, held forces and collision queries). Before, bodies on web only moved inside Editor scenes. See Physics. -
onCollisionis delivered to each node with the other body'sviroTag, the contact point and its normal, as on native. -
applyImpulse,applyTorqueImpulseandsetVelocityon a node's ref. In 3.2.0 an impulse is applied at the centre of mass and an offset warns; 3.2.3 applies torque when you pass an offset. -
Clicks reach the node native would give them to. A press on a child with no
onClickgoes to its nearest ancestor that has one, and a press on a clickable child drags its nearest ancestor withonDrag. -
Changing a node's opacity or visibility no longer resets its position. Position, rotation, scale, opacity and visibility are applied separately, so a dragged or simulated node stays where it is.
In 3.1.0 (viro-web-renderer 1.1.0)
- Update
@reactvision/viro-web-rendererto 1.1.0 alongside ViroReact 3.1.0. - Web AR content hides while tracking is lost, unless
arOptions.hideContentWhenLostisfalse. - Skinned GLBs draw (WebGL refused their bone indices before).
- The usage ping is sent from the web too, except from
localhostand other local hosts.ViroTelemetry.setEnabled(false)turns it off. See Usage Data.
Reliability (3.0.2+)
- Renderer heap grows up to 2 GB (was fixed at 256 MB); glTF loads no longer copy the model — large (~30–40 MB) models no longer black out the scene.
StudioSceneNavigator(web):onAssetError(asset, error),onRendererAbort, andrenderErrorso failures reach your UI; Editor scenes mount once (no double fetch/parse).- Taps are no longer mirrored vertically; transparent image borders no longer hide content behind them.
Related
Updated 6 days ago