Javascript Functions

Refer various functions applicable for WebAR SDK integration

The WebAR’s functions are accessed through the global variable WEBARSDK, which is available after the WebAR SDK script has been loaded. The functions in this page are compatible with A-Frame, BabylonJS & Playcanvas integration if not otherwise specified.

AddMarkerElement()

Usage

WEBARSDK.AddMarkerElement(markerId, entityId);

Description

Associate a specific marker id with an aframe entity's id. When the marker id's image is detected, then the associated aframe entity will be displayed over the marker image.

This API only works with AFrame renderer.

Parameters

Returns

-

Example

WEBARSDK.AddMarkerElement("3b7a4c87-5391-414b-b5b5-72d86292cf28", "marker1");

DisableAutoScale() (deprecated)

Usage

WEBARSDK.DisableAutoScale(disableAutoScaling);

Description

Disables the auto scaling which happens only object is being anchored, only once. (API only works with "Surface-Tracking")

If auto scale is enabled(recommended), the AR object is scaled in such a way that it fits the screen, otherwise the AR object would appear based on the detected surface's extent(which would not be consistent).

This API is deprecated, use API "SetAutoScale()" instead.

Returns

-

Example

WEBARSDK.DisableAutoScale(true);

DisableTracking()

Usage

WEBARSDK.DisableTracking(enableGyroCam);

Description

This function is defined for a portal experience and is used to disable tracking, after the mobile device approaches a portal door, and to start the gyro camera if required. The parameter enableGyroCam is supported only in AFrame rendering engine. It will be ignored for other rendering engines.

Parameters

Returns

-

Example

let closenessRatio = 0.30;

WEBARSDK.SetPortalEntryCallback(() => {
   console.info('Entered the portal door');

   let enableGyroCam =true;

   WEBARSDK.DisableTracking(enableGyroCam);
   console.info('Enabled gyro cam');
 },
closenessRatio);

EnableTrackingOnDesktop()

Usage

WEBARSDK.EnableTrackingOnDesktop(enableTracking);

Description

This function is specifically designed to enable desktop tracking for face tracking scenarios. This function is particularly useful in instances where the application initially starts in a 'lazy-mode' and subsequently determines which tracking mode to initiate. EnableTrackingOnDesktop() activates the face tracking capabilities of the SDK when running on a desktop environment. It is supported only in AFrame rendering engine for face tracking mode. It will be ignored for other rendering engines.

Additionally, desktop tracking can also be controlled via the enable-tracking-on-desktop attribute.

Parameters

Returns

-

Example

WEBARSDK.EnableTrackingOnDesktop(true);

GetActiveMarkerId()

Usage

WEBARSDK.GetActiveMarkerId();

Description

Gets the active marker id i.e. UUID of the current detected marker.

Parameters

-

Returns

Example

const activeMarkerId = WEBARSDK.GetActiveMarkerId();

GetCurrentPose()

Usage

WEBARSDK.GetCurrentPose();

Description

Returns a 4x4 matrix that transforms a stage 3D-object into world-coordinates. Matrix should be accessed in ‘row-major’ order. Please note that tracking assumes a Static-Camera-With-A-Moving-Stage by default. However, it can be changed to Moving-Camera-With-A-Static-Stage using attribute 'static-camera'.

Parameters

-

Returns

Example

const pos_mat = WEBARSDK.GetCurrentPose();
console.info("Pose Matrix", 
pos_mat[0],  pos_mat[1],  pos_mat[2],  pos_mat[3], "\n",
pos_mat[4],  pos_mat[5],  pos_mat[6],  pos_mat[7], "\n",
pos_mat[8],  pos_mat[9],  pos_mat[10], pos_mat[11], "\n",
pos_mat[12], pos_mat[13], pos_mat[14], pos_mat[15]);

GetCurrentPosition()

Usage

WEBARSDK.GetCurrentPosition();

Description

Returns the position of the stage/camera object based on attribute 'static-camera'. Please note that tracking assumes a Static-Camera-With-A-Moving-Stage by default. However, it can be changed to Moving-Camera-With-A-Static-Stage using attribute 'static-camera'.

Parameters

-

Returns

Example

const position = WEBARSDK.GetCurrentPosition();
console.info("Position [x y z] ", position[0],  position[1],  position[2]);

GetCurrentRotation()

Usage

WEBARSDK.GetCurrentRotation();

Description

Returns a 4x4 pure rotation matrix of the stage/camera object based on attribute 'static-camera'. It is the orientation of stage/camera with respect to the world.

Parameters

-

Returns

Example

const rot_mat = WEBARSDK.GetCurrentRotation();
console.info("Pure Rotation Matrix", 
pos_mat[0],  pos_mat[1],  pos_mat[2],  pos_mat[3], "\n",
pos_mat[4],  pos_mat[5],  pos_mat[6],  pos_mat[7], "\n",
pos_mat[8],  pos_mat[9],  pos_mat[10], pos_mat[11], "\n",
pos_mat[12], pos_mat[13], pos_mat[14], pos_mat[15]);

GetCurrentScale()

Usage

WEBARSDK.GetCurrentScale();

Description

Returns the scale of the stage object.

Parameters

-

Returns

Example

const scale = WEBARSDK.GetCurrentScale();
console.info("Scale [sx sy sz] ", scale[0],  scale[1],  scale[2]);

GetLoadingProgress()

Usage

WEBARSDK.GetLoadingProgress();

Description

Returns the app loading progress as a percentage. User may find this useful while creating custom splash screen to create custom animation for loading progress.

Parameters

-

Returns

Example

const loadingProgress = WEBARSDK.GetLoadingProgress();

GetMouthOpenedMagnitude()

Usage

WEBARSDK.GetMouthOpenedMagnitude();

Description

Returns the magnitude of the distance between the upper and lower lips when the mouth is opened. For example, it can be used to trigger some animation of the webar-face model, if the magnitude is greater than 0.2.

Parameters

-

Returns

Example

const mouthOpenedMgtd = WEBARSDK.GetMouthOpenedMagnitude();

RemoveMarkerElement()

Usage

WEBARSDK.RemoveMarkerElement(markerId);

Description

Removes the association of a marker id with an entity in the scene and the user will not be able to see any AR object when the marker id's image is detected.

This API only works with AFrame renderer.

Parameters

Returns

-

Example

WEBARSDK.RemoveMarkerElement("3b7a4c87-5391-414b-b5b5-72d86292cf28");

Init()

Usage

<script src="<path_to_webar_sdk_min_js>"
  auto-init="false">
</script>

WEBARSDK.Init();

Description

If the SDK script attribute auto-init is set to 'false', then tracking has to be started manually by calling Init() method. For example, this will be useful when the user has to display some information in an overlaid html div, and only after the user clicks a button to enter into the 'Surface Tracking' or 'Marker Tracking' experience.

InitBabylonJs()

Usage

WEBARSDK.InitBabylonJs(canvasElement, sceneObject, cameraMeshObject, stageMeshObject | webarMarkerMeshMapArray, webarUXControlMesh);

Description

This function is used to initialise the SDK with BabylonJs scene Objects for Surface Tracking or Marker Tracking experience.

Parameters

Returns

-

Example

Babylon.Js Example. Refer Section on surface tracking and marker tracking.

SetAppReadyCallback()

Usage

WEBARSDK.SetAppReadyCallback(callbackFunction);

Description

This function is used to set a callback function when app is completely loaded. For example, this callback function can be used to fade out the custom animation of splash screen.

Parameters

Returns

-

Example

WEBARSDK.SetAppReadyCallback(() =>{
   console.info('App is ready');
});

SetARModelPlaceCallback()

Usage

WEBARSDK.SetARModelPlaceCallback(callbackFunction);

Description

The SetARModelPlaceCallback function is designed to register a callback function that triggers when an AR model is successfully placed within the scene. This allows developers to define custom behavior that occurs immediately after the model placement, such as initiating animations, logging events, or enabling additional UI elements.

Parameters

This function's utility is predicated on the webar-ux-control being properly set up with stageCursorUX set to true in the scene. Without this configuration, the reset button—and consequently the reset callback—will not function. (Only for AFrame & BabylonJS)

Returns

-

Example

WEBARSDK.SetARModelPlaceCallback(() =>{
   console.info('AR Model is placed');
});

SetAutoMarkerDetectionStyle()

Usage

WEBARSDK.SetAutoMarkerDetectionStyle(autoMarkerUX, showScanInstructionText);

Description

This function is used to overlay auto marker detection default style, user can use custom user experience to enhance visuals. User can also pass a flag to disable the scan instruction text

Parameters

Returns

-

Example

WEBARSDK.SetAutoMarkerDetectionStyle(autoMarkerUX, showScanInstructionText);

SetAutoScale()

Usage

WEBARSDK.SetAutoScale(bEnable=true);

Description

Auto Scale is enabled by default. To disable the auto scale, pass boolean 'false' in the argument and call this function after Init().

What is Auto Scaling in context of 'Marker Tracking' & 'Surface Tracking'?

  1. **Marker Tracking:**The scaling is applied in such a way that a (1,1) unit plane fits the width/height of the marker(where unit is meter).

  2. **Surface Tracking:**It scales the AR object based on distance from the camera

Parameters

Returns

-

Example

WEBARSDK.SetAutoScale(false);

SetEyesMeshFilled()

Usage

WEBARSDK.SetEyesMeshFilled(false);

Description

If set to false, the eyes area of the facemesh appears hollow .i.e no texture/material is rendered on the both the eyes area. If set to true, eyes of the facemesh appears closed.

Parameters

Returns

-

Example

WEBARSDK.SetEyesMeshFilled(true);

SetFaceScaleFactor()

Usage

WEBARSDK.SetFaceScaleFactor(scaleFactor);

Description

This function configures the scale at which AR objects are displayed relative to the user’s face in a web-based AR experience. It computes a scale factor based on the bounding box dimensions of a reference model (e.g., human-head) and applies this scale factor to the webar-face and webar-face-pivot entities. As a result, all AR objects that are children of these entities will have their scale and position adjusted according to the scale factor, ensuring the AR objects appear proportionally shrinked or enlarged as necessary.

Parameters

Returns

-

Example

// Asynchronously load the reference model and calculate its bounding box
let refModel = await loadModel('models/human-head.glb');
const bbox = new THREE.Box3().setFromObject(refModel);
const size = bbox.getSize(new THREE.Vector3());

// Calculate the scale factor from the x dimension of the bounding box
let scaleFactor = 1 / size.x;
console.log('Calculated scale Factor = ', scaleFactor);

// Apply the calculated scale factor to the webar-face entities
WEBARSDK.SetFaceScaleFactor(scaleFactor);

SetGuideAnimation()

Usage

WEBARSDK.SetGuideAnimation(pathURL);

Description

This function is used to set custom guide animations for surface tracking and marker tracking (only with scan button). Please note that it only supports lottie animations json format.(https://lottiefiles.com)

Parameters

Returns

-

Example

WEBARSDK.SetGuideAnimation("https://assets4.lottiefiles.com/packages/lf20_lir7pmho.json");

SetGuideViewCallbacks()

Usage

WEBARSDK.SetGuideViewCallbacks(startGuideViewCallback, stopGuideViewCallback);

Description

This API gives a callback once the surface tracking experience loads (Splash screen) and when the default Hand with phone animation guide starts(startGuideViewCallback) and then stops/hides (stopGuideViewCallback) after a surface is detected.

If you want to display a custom Hand with phone/Surface detection guide, set the SDK attribute show-guide-view="false", and use the two callback parameters passed via startGuideViewCallback and stopGuideViewCallback, to show and then hide it.

Other cases of using these callbacks are:

  • A custom loading splash/progress full screen div element can be overlaid and can be removed/hidden after startGuideViewCallback is received

  • Start the animation of a 3D model after stopGuideViewCallback is received.

Example

WEBARSDK.SetGuideViewCallbacks(
  startGuideViewCallback = ()=>{
    console.log("Start(ed) hand guide animation");
    // TODO: Show custom hand with phone animation guide, if show-guide-view set to false
  },
  stopGuideViewCallback = ()=>{
    console.log("Stop(ped) hand guide animation");
    // TODO: Hide custom hand with phone animation guide, if show-guide-view set to false
  }
);ja

SetMarkerDetectedCallback()

Usage

WEBARSDK.SetMarkerDetectedCallback(callbackFunction);

Description

This is used to set a callback function when the 3D object appears on the screen after a marker image is detected. For example, this callback function can be used to start the animation of the 3D model.

Parameters

Returns

-

Example

WEBARSDK.SetMarkerDetectedCallback((markerId) =>{
   console.info('Marker detected for marker id:', markerId);
});

SetMarkerLostCallback()

Usage

WEBARSDK.SetMarkerLostCallback(callbackFunction);

Description

This is used to set a callback function when a marker image tracking is lost.

Parameters

Returns

-

Example

WEBARSDK.SetMarkerLostCallback((markerId) =>{
   console.info('Marker is lost for marker id: ', markerId);
});

SetMouthMeshFilled()

Usage

WEBARSDK.SetMouthMeshFilled(false);

Description

If set to false, the mouth area of the facemesh appears hollow .i.e no texture/material is rendered on the mouth area. If set to true, mouth of the facemesh is closed.

Parameters

Returns

-

Example

WEBARSDK.SetMouthMeshFilled(true);

SetPortalEntryCallback()

Usage

WEBARSDK.SetPortalEntryCallback(callbackFunction, closenessRatio);

Description

This is a portal experience and is used to set a callback function when the mobile device approaches a 3D portal/door entrance.

Parameters

The callback function for when the mobile device approaches a 3D object.

Returns

-

Example

let closenessRatio = 0.30;

WEBARSDK.SetPortalEntryCallback(() => {
   console.info('Entered the portal');
 },
closenessRatio);

SetResetButtonCallback()

Usage

WEBARSDK.SetResetButtonCallback(callbackFunction);

Description

This function is designed to link a user-defined callback to the reset button's action within an AR interface. When the reset button is pressed, the specified callback function is executed, allowing developers to implement custom logic such as resetting the scene, clearing user progress, or other application-specific reset behavior.

Parameters

This function's utility is predicated on the webar-ux-control being properly set up with stageCursorUX set to true in the scene. Without this configuration, the reset button—and consequently the reset callback—will not function. (Only for AFrame & BabylonJS)

Returns

-

Example

WEBARSDK.SetResetButtonCallback(() => {
   console.info('Reset button is clicked');
 });

SetResetButtonVisibility()

Usage

WEBARSDK.SetResetButtonVisibility(isVisible);

Description

The SetResetButtonVisibility function controls the display of the reset button within the AR interface. It provides the ability to dynamically show or hide the reset button based on the needs of the AR experience or user preferences.

Parameters

Returns

-

Example

// Call this function to make the reset button visible
WEBARSDK.SetResetButtonVisibility(true);

// Call this function to hide the reset button
WEBARSDK.SetResetButtonVisibility(false);

SetStageReadyCallback()

Usage

WEBARSDK.SetStageReadyCallback(callbackFunction);

Description

This function is used to set a callback function when the object appears for the first time on screen after the surface. For example, this callback function can be used to start the animation of the 3D model.

Parameters

This is the callback function that gets called when the 3D object appears on screen for the first time after the surface has been detected.

Returns

-

Example

WEBARSDK.SetStageReadyCallback(() =>{
   console.info('Stage is ready now!!!');
});

SetTrackingQualityChangeCallback()

Usage

WEBARSDK.SetTrackingQualityChangeCallback(callbackFunction);

Description

This is used to set a callback function when either 'Surface' or 'Marker' tracking quality gets changed.

Parameters

Returns

-

Example

WEBARSDK.SetTrackingQualityChangeCallback((trackingQuality) =>{
   console.info('Tracking quality: ', trackingQuality);
});

SetTrackingStartedCallback()

Usage

WEBARSDK.SetTrackingStartedCallback(callbackFunction);

Description

This function is used to set a callback function which gives a callback when either 'Surface' or 'Marker' tracking has started.

Parameters

Returns

-

Example

WEBARSDK.SetTrackingStartedCallback(() =>{
   console.info('Tracking has started');
});

SetTrackingStoppedCallback()

Usage

WEBARSDK.SetTrackingStoppedCallback(callbackFunction);

Description

This function is used to set a callback function which gives a callback when either 'Surface' or 'Marker' tracking has stopped.

Parameters

Returns

-

Example

WEBARSDK.SetTrackingStoppedCallback(() =>{
   console.info('Tracking has stopped');
});

StartTracking()

Usage

WEBARSDK.StartTracking(keepARAfterLost = false);

Description

This function is used to start the tracking, if tracking has stopped or param 'auto-start' is set to 'false'. It either starts Surface or Marker Tracking based on the 'webar-mode' attribute.

auto-init is associated with initializing the sdk core whereas auto-start enables the user to control when to start the tracking in the app.

Parameters

Returns

-

Example

<script src="<path_to_webar_sdk_min_js>"
auto-start="false">
</script>

WEBARSDK.StartTracking(true);

StopTracking()

Usage

WEBARSDK.StopTracking(keepARVisible = false);

Description

This function is used to stop the tracking, if tracking has already started.

auto-init is associated with initializing the sdk core whereas auto-start enables the user to control when to start the tracking in the app.

Parameters

Returns

-

Example

WEBARSDK.StopTracking(true);

SetUserGestureRotation()

Usage

WEBARSDK.SetUserGestureRotation(enabled);

Description

This function allows you to enable or disable user rotation.

Parameters

Returns

-

Example

WEBARSDK.SetUserGestureRotation(true);

SetUserGestureScale()

Usage

WEBARSDK.SetUserGestureScale(enabled);

Description

This function enables or disables user scaling.

Parameters

Returns

-

Example

WEBARSDK.SetUserGestureScale(true);

SetWebARMode()

Usage

WEBARSDK.SetWebARMode(tracking-mode);

Description

This function is used to set the webar mode at a delayed stage of application. It provides a dynamic loading using lazy initialisation. It should be called only-if webar-mode script attribute is specified with 'lazy-mode'.

This method has to be called before StartTracking().

Parameters

Returns

-

Example

WEBARSDK.SetWebARMode(trackingMode);

TakeSnapShot()

Usage

WEBARSDK.TakeSnapShot(callback, canvas);

Description

This function is used to capture a snapshot of the AR experience.

Only for Playcanvas! To get the snapshot API to work correctly in Playcanvas rendering engine, enable Preserve Drawing Buffer flag. Go to Playcanvas Project Editor, then navigate to project SETTINGS > RENDERING tab and make sure "Preserve Drawing Buffer" is checked.

Parameters

Returns

-

Example

    <script>
        var captureCanvas = document.createElement('canvas');
        captureCanvas.setAttribute('id', 'captureCanvas');

        // Set a timer to take auto snapshot after 10 seconds and download it as a PNG file.
        setTimeout(() => {
            console.log('Taking photo');

            WEBARSDK.TakeSnapShot(() => {
                const link = document.createElement("a");
                link.download = "ar_snapshot.png";
                link.target = '_blank';
                link.href = captureCanvas.toDataURL('image/png');
                link.click();
            }, captureCanvas);
        },
        10000);

    </script>