This reference is hand-written from the source and the shipped
type declarations (src/*.d.ts, kept honest against the
implementation by tsc --checkJs). Where the JSDoc in the code
disagrees with the implementation, this page documents the
implementation and says so.
Package exports
import ARCore, {
ARError,
ARView,
createARView,
createARGestureController,
takeScreenshot,
enableCustomization,
addTextures,
switchModel,
placeModel,
} from 'reticlexr';
import { useARCore } from 'reticlexr/react';
import { ARCoreWeb } from 'reticlexr/web';| Export | Kind | Layer |
|---|---|---|
ARCore (default) | Native facade object | Capacitor bridge → Android / iOS native plugin (web → WebXR engine) |
ARView, createARView | Class + factory | High-level facade over the WebXR engine |
takeScreenshot, enableCustomization, addTextures, switchModel, placeModel, moveModel | Functional helpers (view-first) | Same facade, function style |
useARCore | React hook (import from reticlexr/react) | WebXR engine mirrored into React state |
ARCoreWeb | Engine class (import from reticlexr/web) | The WebXR runtime itself |
createARGestureController | Factory | Standalone Pointer Events controller |
ARError, codedError | Error class + factory | The package's one error convention |
Subpaths: ., ./react, ./web, ./ar-view, ./gestures,
./package.json. Deep imports outside the exports map do not
resolve.
Note
One identifier everywhere: a placed model is a modelId on
every layer and runtime. anchorId survives as a
deprecated alias, the same string, on inputs, results and
event payloads, and is removed in the next major version.
ARCore native facade
The default export. Every method delegates to the Capacitor plugin
registered as ARCore — on Android and iOS that's the native
plugin (the iOS plugin's jsName is also ARCore), on
web it falls through to the WebXR engine (ARCoreWeb). Failures
reject with an ARError carrying a stable code (a runtime code
when one exists, otherwise a per-method *_FAILED fallback);
checkSupport resolves a result object instead.
import ARCore from 'reticlexr';
const support = await ARCore.checkSupport();
if (support.supported) {
await ARCore.startSession({ planeDetection: true, lightEstimation: true });
const hit = await ARCore.hitTest({ x: 0.5, y: 0.5 });
await ARCore.stopSession();
}| Method | Signature | Returns |
|---|---|---|
startSession | (options?: { planeDetection?, lightEstimation?, overlay? }) | Promise<{ success: boolean }> |
stopSession | () | Promise<void> |
hitTest | (options: { x: number, y: number }) (normalised [0, 1]) | Promise<{ hit, position?, rotation?, planeType?, error? }> |
placeModel | (options: { modelPath: string, hitId?: string } | { modelUrl: string, hitId?: string }) — plus iOS-only usdzPath?: string / usdzUrl?: string | Promise<{ modelId: string, anchorId: string }> |
setTransform | (options: { modelId, rotation?: {x,y,z} degrees, scale?: number }) | Promise<void> |
setMaterial | (options: { modelId, color: string }) (hex colour) | Promise<void> |
moveModel | (options: { modelId, x: number, y: number }) | Promise<Object> |
beginDragMove | (modelId: string) | boolean |
updateDragPoint | (x: number, y: number) (normalised [0, 1]) | void |
endDragMove | () | void |
removeModel | (options: { modelId }) | Promise<void> |
getPlacedModels | () | Promise<Array<{ modelId, modelUrl, position, rotation, scale }>> |
clearModels | () | Promise<void> |
checkSupport | () | Promise<{ supported: boolean, reason: string, code?: string }> |
on | (eventType: string, callback: (data) => void) | unsubscribe function () => void |
addListener | (eventType, callback) | Capacitor listener handle (internal) |
Warning
Native-runtime scope differs by platform. Android (Option B):
the session, hit test and events are real; checkSupport returns
the actual ArCoreApk.checkAvailability() result and a successful
hit test creates a real ARCore anchor. But the Android plugin does
not render models: placeModel, moveModel, setTransform,
setMaterial, removeModel, getPlacedModels and clearModels
reject with code NOT_IMPLEMENTED — WebXR renders models there.
iOS (since 1.2.0): there is no WebXR, so the iOS plugin
(ARKit + RealityKit) implements the model methods for real:
placement, transforms, material colour, move, remove, list and
clear all operate on RealityKit entities anchored to ARAnchors,
and the event set is the same as Android's. iOS models are
USDZ: placeModel takes the GLB source as usual plus optional
usdzPath / usdzUrl (explicit iOS source, takes precedence);
without them, a .usdz sibling next to the GLB is used, and if no
USDZ exists the call rejects with MODEL_FORMAT_UNSUPPORTED.
Other iOS codes: CAMERA_PERMISSION_DENIED,
SESSION_NOT_ACTIVE, NO_SURFACE, MODEL_NOT_FOUND,
MODEL_LOAD_FAILED, INVALID_COLOR,
UNSUPPORTED_DEVICE_NOT_CAPABLE. On iOS, getPlacedModels
still resolves to the same array of
{ modelId, anchorId, modelUrl, position, rotation, scale }
entries (the facade unwraps the native bridge's { models }
dictionary). See
WebXR vs native ARCore.
startSession option: overlay (iOS, since 1.3.0)
overlay: true runs the iOS AR view below a transparent web
view instead of fullscreen over it, so the app's own page —
product cards, colour swatches, Add to Cart — renders over the
camera feed (the arrangement WebXR's DOM overlay gives Android).
Default false is the fullscreen behaviour, unchanged; the
option is ignored on Android and web.
Two requirements/consequences on the host app:
- Transparent page background. The plugin clears the native
web view layers (and restores them exactly on
stopSession), but the page must also make its own document/body background transparent while the session runs, or the page's background will cover the camera feed. - JS-driven taps. The frontmost web view receives all
touches in overlay mode, so RealityKit gestures on placed
models do not fire (the plugin skips installing them). Forward
taps as normalised coordinates to
hitTest/placeModel/moveModel, and manipulate models withsetTransform/setMaterial.
Facade events
ARCore.on(eventType, callback) subscribes to the local event bus,
fed by the native event bridge, which installs lazily on the
first subscription (importing the package has no listener side
effects):
const off = ARCore.on('modelPlaced', (data) => console.log(data));
off(); // unsubscribeWired event types: sessionStarted, trackingChanged,
surfaceDetected, surfaceLost, surfaceUpdated, sessionStopped,
modelPlaced, modelRemoved, modelTransformed,
modelMaterialChanged, modelMoved, error. Events are per
runtime; the WebXR engine emits its own set through its listeners
(below), never through ARCore.on.
ARView and createARView
The framework-agnostic facade over one WebXR engine instance. This is the API the guides and the example use.
import { createARView } from 'reticlexr';
const ar = createARView({ overlay: document.querySelector('#ar-overlay') });Constructor options: { engine?, overlay? }, where engine is an
ARCoreWeb instance (default: a new one), overlay the DOM
element for the immersive session's overlay.
Session
| Member | Signature / behaviour |
|---|---|
checkSupport() | → engine checkSupport() → { supported, reason, code? } |
create(options?) | Starts the session. Options: { overlay?, showReticle = true, showPlaneDots = true, dotSpacing = 0.14, dotSize = 0.014, showShadow = true, planeDetection = false, lightEstimation = false, anchors = false, enableScreenshots = false, framebufferScale = 1, ktx2TranscoderPath = null }. The default session requests hit-test only (Tier 0); plane detection, light estimation and anchors are opt-in tiers. Resolves { success, hasOverlay, planeDetection } |
destroy() | Destroys gestures, then fully disposes the engine (engine.dispose()) |
onFrame(cb) / onPlanes(cb) | Subscribe to engine frame / plane listeners; both return an unsubscribe function |
getSurface() | Current surface state { hasSurface, position, rotation, planeType, confidence } |
getPlanes() | [{ orientation, polygon: [{x, y, z}] }] |
setReticleVisible(v) / setSurfaceDotsVisible(v) | Visibility toggles |
await ar.create({ showReticle: true, showPlaneDots: true, dotSpacing: 0.14 });
const off = ar.onPlanes((e) => console.log(e.total, 'planes'));
console.log(ar.getSurface().planeType); // e.g. 'horizontal'
await ar.destroy();
off();Models
| Member | Signature / behaviour |
|---|---|
preloadModels(urls) | Loads each URL into the engine cache (Promise.all) |
placeModel(modelUrl, options?) | Options: { position?, rotation?, x = 0.5, y = 0.5, scale? }. Hit-tests (centre, or x, y) unless position is given. Resolves { success: true, modelId, … } or { success: false, code: 'NO_SURFACE', reason } (reason is a deprecated alias of code). Sets activeModelId / activeModelUrl |
switchModel(modelUrl, options?) | Options: { preserveMaterial = true }. Keeps placement/transform; falls back to placeModel when nothing is placed |
moveModel(point?) | Moves the active model to the surface under a normalised screen point ({ x = 0.5, y = 0.5 }). Keeps its scale. Resolves { success: false, code: 'NO_SURFACE' } on a miss; the model stays put |
removeModel() | Removes the active model; no-op if none |
getPlacedModels() | Models placed through this view |
clearModels() | Removes every model placed through this view |
setScale(scale) | Clamped to [0.1, 5], applied uniformly |
rotateBy(radians) | Accumulates transform.rotationY, applies a Y rotation |
setColor(color) | Sets the active model's colour (hex string) |
addTextures({ name: url }) | Registers named texture URLs; returns this |
applyTexture(nameOrUrl, options?) | Options: { materialName? }. Throws if no model is placed |
takeScreenshot(options?) | Delegates to the engine, see Screenshots |
| Public fields | activeModelId, activeModelUrl, placedModelUrls (Map), transform ({ scale, rotationY }), textures (a Map) |
await ar.preloadModels(['/models/sofa.glb', '/models/chair.glb']);
const placed = await ar.placeModel('/models/sofa.glb');
if (placed.success) {
ar.setScale(1.25);
ar.rotateBy(Math.PI / 6);
await ar.switchModel('/models/chair.glb'); // same anchor, scale, rotation
await ar.setColor('#222b3c');
await ar.removeModel();
}Customization and gestures
enableCustomization(options?) wires the gesture controller to
the overlay. It throws without an overlay. Options:
{ modelUrl: string | (() => string), onTap?, onScale?, onRotate?, onError? }: modelUrl may be a URL string or a
function invoked on every tap; placement errors are delivered to
onError. Returns a cleanup function. Full details in
Gestures.
Functional helpers
The same operations, view-first, for function-style codebases:
import { placeModel, switchModel, addTextures, enableCustomization, takeScreenshot } from 'reticlexr';
await placeModel(ar, '/models/sofa.glb');
await switchModel(ar, '/models/chair.glb', { preserveMaterial: false });
addTextures(ar, { oak: '/textures/oak.jpg' });
const cleanup = enableCustomization(ar, { modelUrl: () => '/models/sofa.glb' });
const shot = await takeScreenshot(ar, { format: 'jpeg', quality: 0.85 });ARCoreWeb engine
The WebXR engine class behind everything above
(import { ARCoreWeb } from 'reticlexr/web'). Advanced consumers
can use it directly; the hook does.
Configuration
setConfig(partial) / getConfig(). Defaults:
| Key | Default | Key | Default |
|---|---|---|---|
showReticle | true | reticleColor | 0x00ff88 |
showPlanes | false | reticleColorVertical | 0xff6b6b |
showPlaneDots | true | planeColorHorizontal | 0x00ff88 |
showShadow | true | planeColorVertical | 0xff6b6b |
showBaseRing | false | shadowOpacity | 0.4 |
dotSize | 0.02 | shadowSize | 1.2 |
dotSpacing | 0.1 | debug | false |
modelCacheLimit | 20 |
Note
The facade's create() overrides some of these per view (dots at
spacing 0.14, size 0.014). Engine defaults apply when you drive
the engine directly. debug gates the engine's diagnostic
logging; modelCacheLimit caps the GLTF cache (LRU; entries with
live placements are never evicted).
Session and accessors
checkSupport(), startSession({ planeDetection = false, lightEstimation = false, anchors = false, enableScreenshots = false, framebufferScale = 1, ktx2TranscoderPath = null, domOverlay = null }), stopSession(), dispose() (full
teardown; the instance can start again), clearModelCache(),
getSession(), getRenderer(), getScene(), getCamera(),
getAnchors().
Models
| Method | Signature / behaviour |
|---|---|
loadModel(url) | Loads (or returns the cache entry) and resolves a fresh gltf.scene.clone() |
placeModel({ modelUrl, position?, rotation?, scale? }) | Resolves { modelId, anchorId } (anchorId = deprecated alias). Inputs are normalised: position [x,y,z] or {x,y,z}; rotation quaternion or Euler radians; scale number/array/object, clamped to [0.1, 5] per axis |
removeModel({ modelId }) | Removes the model; disposal follows the ownership rule |
getPlacedModels() | [{ modelId, modelUrl, position, rotation, scale }] |
clearModels() | Removes every placed model |
transformModel({ modelId, position?, rotation?, scale? }) | Applies a model transform |
switchModel({ modelId, modelUrl, preserveMaterial = true }) | Swaps the model on an existing placement; material carry-over matches by name, then order |
setModelColor({ modelId, color }) | Recolours |
setModelMaterial({ modelId, metalness?, roughness?, opacity? }) | PBR property update |
setModelTexture({ modelId, textureUrl, materialName? }) | Applies a texture |
setTransform(options) / setMaterial(options) / moveModel(options) | Facade-compatibility shims accepting modelId (or its anchorId alias); a plain {x,y,z} rotation in setTransform is Euler degrees |
const { modelId } = await engine.placeModel({
modelUrl: '/models/sofa.glb',
position: [0, 0, -1.5],
rotation: [0, 0, 0, 1], // quaternion
scale: [1, 1, 1],
});
await engine.setModelMaterial({ modelId, roughness: 0.8 });
await engine.removeModel({ modelId });Queries, events and visualisation
| Method | Behaviour |
|---|---|
hitTest({ x, y }) | Resolves { hit, position?, rotation?, planeType?, code? }. Centre coordinates use the reticle path; non-centre coordinates perform a ray-based hit test |
hitTestAtPoint(x, y) | The ray-based hit test directly |
getSurfaceState() / getSurfaceDetectionState() | Current surface state |
getDetectedPlanes() | Detected plane list |
addFrameListener(cb) / addPlaneListener(cb) | Subscribe; return unsubscribe |
setReticleVisible(v) | Toggle the reticle |
setPlaneVisualization(v) / isPlaneVisualizationEnabled() | Plane mesh visualisation |
setShadowVisible(modelId, v) | Per-model shadow toggle |
setShadowConfig({ enabled?, opacity?, size? }) / getShadowConfig() | Shadow tuning |
Frame listeners receive engine events: surfaceDetected,
surfaceLost, modelPlaced, modelRemoved, modelTransformed,
modelColorChanged, modelSwitched, sessionEnded: payloads
carry modelId (with anchorId as its deprecated alias). Plane
listeners receive planeAdded and planesUpdated with payload
{ type, total, horizontal, vertical }: counts as numbers.
Screenshots
takeScreenshot({ format = 'png', quality = 0.92, width?, height?, includeReticle? }) resolves { success, dataUrl, width, height, timestamp, includesCamera } or { success: false, code?, error }. Including the camera feed needs the session started
with enableScreenshots: true, see
Screenshots.
useARCore
React hook over the WebXR engine, imported from
reticlexr/react. By default all consumers share one
lazily-constructed engine; pass { engine } (a dedicated
ARCoreWeb from reticlexr/web) for an isolated, per-instance
hook. It checks support on mount and mirrors engine events into
state.
State: isSupported: boolean | null, isSessionActive: boolean, placedModels: Array<{ modelId, modelUrl, position, rotation, scale }>, error: string | null, detectedPlanes: { horizontal, vertical, total }, surfaceState: { hasSurface, position, rotation, planeType, confidence }.
Methods (all memoised): startSession(options) →
Promise<boolean> (options pass straight to the engine, e.g.
{ domOverlay }), stopSession(), hitTest(x, y) (normalised
[0, 1], origin top-left, not pixels),
placeModel(modelUrl, position, rotation, scale),
removeModel(modelId), getPlacedModels(), clearModels(),
transformModel(modelId, transforms),
setModelColor(modelId, color),
setModelMaterial(modelId, properties), setConfig /
getConfig, setShadowConfig / getShadowConfig,
setShadowVisible(modelId, v), getDetectedPlanes(),
setReticleVisible(v), setPlaneVisualization(v),
clearError(), getRenderer / getScene / getCamera,
takeScreenshot(options).
import { useARCore } from 'reticlexr/react';
const ar = useARCore();
await ar.startSession({ domOverlay: overlayElement });
await ar.placeModel('/models/sofa.glb', [0, 0, -1.5], [0, 0, 0, 1], [1, 1, 1]);
// Placed models (with their modelIds) are mirrored into state:
const first = ar.placedModels[0];
if (first) ar.setModelColor(first.modelId, '#a55f3b');Note
Transform arguments are normalised: positions accept
[x, y, z] or {x, y, z}, rotations a quaternion array/object or
Euler radians, scales a number, array or object. (In 1.0.0,
{x, y, z} objects produced NaN transforms, fixed in 1.1.0.) With the shared default engine, one consumer
stopping the session stops it for all consumers; mount the hook
once, or pass a dedicated engine per view.
Gesture controller
import { createARGestureController } from 'reticlexr';
const gestures = createARGestureController({
element, // required: throws if missing
onTap, onDrag, onPinch, onRotate,
tapMaxDuration = 260, // ms
tapMaxDistance = 12, // px
preventDefault = true,
ignoreSelector = '[data-ui]',
});
gestures.destroy();Payloads: onTap({ x, y }), onDrag({ dx, dy, x, y }),
onPinch({ factor, center }) with an incremental factor,
onRotate({ delta, center }) with an incremental delta in
radians. Full guide: Gestures.
Error conventions
One convention across the package: async methods reject
with an ARError, an Error with a stable, machine-readable
code. Result-object APIs resolve with the same code on their
failure results. Messages may change; codes are the contract.
| Layer | Convention |
|---|---|
ARCore facade | Rejects with ARError (runtime code preserved; per-method *_FAILED fallback); checkSupport resolves { supported: false, reason, code } |
Engine hitTest | Resolves { hit: false, code, error } |
ARView.placeModel | Resolves { success: false, code, reason } (reason = deprecated alias of code) |
useARCore | Sets error state; failure results carry code |
| Screenshots | Resolve { success: false, code, error } |
Engine codes include SESSION_START_FAILED,
SESSION_NOT_ACTIVE, SESSION_ENDED, HIT_TEST_FAILED,
HIT_TEST_TIMEOUT, HIT_TEST_UNAVAILABLE, NO_VIEWER_POSE,
MODEL_NOT_FOUND, MODEL_URL_REQUIRED, MODEL_LOAD_FAILED,
NO_SURFACE, NO_ACTIVE_MODEL, OVERLAY_REQUIRED,
CAMERA_CAPTURE_UNAVAILABLE, CAPTURE_BUSY, INSECURE_CONTEXT,
plus native codes surfaced unchanged (e.g. NOT_IMPLEMENTED,
ACTIVITY_UNAVAILABLE on Android; MODEL_FORMAT_UNSUPPORTED,
CAMERA_PERMISSION_DENIED, UNSUPPORTED_DEVICE_NOT_CAPABLE on
iOS).
Model and texture URLs
Model and texture URLs are loaded as given (three.js
GLTFLoader / TextureLoader); the package performs no
validation or allow-listing. Only load models and textures from
sources you control or trust; a GLB is parsed in your page's
origin, so an untrusted file is untrusted content. Cross-origin
URLs need CORS (Access-Control-Allow-Origin, over HTTPS) or
the load fails; same-origin or bundled assets avoid the issue.
Deprecated aliases
All aliases keep working throughout 1.x and are removed in the next major version.
| Deprecated | Replacement |
|---|---|
anchorId (inputs, results, event payloads) | modelId, the same string |
modelPath (engine placeModel option) | modelUrl |
reason (ARView place result) | code, the same string |
useARCore from the package root | useARCore from reticlexr/react |