Javascript Functions

Refer various functions applicable for WebAR SDK integration

spaceBlippar Documentation Centre

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

ParameterTypeDescription

markerId

uuid

Marker id value obtained from the Blippar Hub Manager after uploading an image.

entityId

string

Value of id attribute of html element.

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.

ParameterTypeDescription

disableAutoScaling

boolean

if true, disables the autoscale if false, enables the autoscale.

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

ParameterTypeDescription

enableGyroCam

(This parameter works only for AFrame)

boolean

If true, disables surface tracking and starts A-Frame’s gyro camera.

If false, disables surface tracking but does not start A-Frame’s gyro camera. The camera’s position is not updated.

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

ParameterTypeDescription

enableTracking

boolean

If true, enables face tracking on desktop

If false, disables surface tracking on desktop if already enabled by enable-tracking-on-desktop

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

ReturnsTypeDescription

markerId

string

'marker-id' i.e. uuid string of the detected marker i.e. value obtained from the Blippar Hub Manager after uploading respective marker image. Returns empty string "", if there is no active marker.

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

ReturnsTypeDescription

poseMatrix

array matrix

The first 3x3 sub-matrix describes the rotation and the first-3 entries of the last column describe the position (location of stage-object).

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

ReturnsTypeDescription

position

Float32Array

Array of size 3 in order [x, y z] where x, y & z denotes the position on x-axis, y-axis & z-axis respectively.

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

ReturnsTypeDescription

rotationMatrix

Float32Array

The first 3x3 sub-matrix describes the rotation.

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

ReturnsTypeDescription

scale

Float32Array

Array of size 3 in order [sx, sy sz] where sx, sy & sz denotes the scale of the stage object in x-axis, y-axis & z-axis respectively.

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

ReturnsTypeDescription

loadingProgress

float

Loading progress of application

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

ReturnsTypeDescription

magnitude

float

Returns the magnitude of the distance between the upper and the lower lips when the mouth is opened. Its typical value ranges from 0.0 to 2.0

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

ParameterTypeDescription

markerId

uuid

Marker id value obtained from the Blippar Hub Manager after uploading an image.

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

ParameterTypeDescription

canvasElement

DOM Element object

DOM Element object of the html canvas element which is used by the Babylon rendering engine.

sceneObject

Babylon Scene object

Scene object created using Babylon

cameraMeshObject

Babylon UniversalCamera object

UniversalCamera object created using Babylon

stageMeshObject | webarMarkerMeshMapArray

Babylon Mesh object (or) Array of JS objects

Surface Tracking

In surface-tracking webar-mode, a stageMeshObject has to be passed.

A stageMeshObject is an empty Babylon mesh which has to be set as the parent for the 3D objects that have to be displayed on the surface.

(or)

Marker Tracking

In marker-tracking webar-mode, a webarMarkerMeshMapArray has to be passed.

A webarMarkerMeshMapArray is an array of Marker Mesh Map objects and it has the following structure:

[
  {
    markerId   : <marker id 1>
    markerMesh : <Babylon Mesh 1>
  },
  {
    markerId : <marker id 2>
    markerMesh : <Babylon Mesh 2>
  }
]

Please see this example on how to construct and pass a Marker Mesh Map Array.

webarUXControlMesh

Babylon Mesh object

Surface Tracking(optional)

To activate interactive user experience (UX) in surface-tracking mode, a webarUXControlMesh must be used. This empty Babylon mesh is attached as a child to the stageMeshObject, adding a stage cursor for precise AR model placement. It also enables gesture-based interactions like rotation and scaling, making the scene more interactive and engaging.

// Create a 'webar-ux-control' Mesh
var webarUXControl = new BABYLON.Mesh("webar-ux-control", scene);
webarUXControl.setParent(webarStage); // Set webarStage as parent to webarUXControl mesh

// Set webar options to enable stage cursor UX, user gesture rotation, and scaling
webarUXControl.webarOptions = {
    stageCursorUX: true,
    userGestureRotation: true,
    userGestureScale: true
};

The webarOptions property of the webarUXControl mesh manages interactive features. Activating stageCursorUX displays a placement cursor, while userGestureRotation and userGestureScale enable intuitive model interactions.

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

ParameterTypeDescription

callbackFunction()

function

Callback function which can be used to define custom behaviour when gyro and camera is ready to be used.

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

ParameterTypeDescription

callbackFunction()

function

Callback function which can be used to define custom behaviour when AR Object is placed.

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

ParameterTypeDescription

autoMarkerUX

html element

HTML div element contains custom visual code

showScanInstructionText

boolean

A boolean flag to enable/disable the scan instructions appear at the bottom of the screen when auto marker detection is enabled. e.g.

'Look for a marker to scan...'

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

ParameterTypeDescription

bEnable

boolean

flag to disable/enable the auto scaling, by default auto scaling is enabled

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

ParameterTypeDescription

fillEyesArea

boolean

false - Eyes area appears hollow.

true - Eyes area appears filled.

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

ParameterTypeDescription

scaleFactor

float

A value calculated as the inverse of the x dimension of the bounding box of the reference model. It is applied as a uniform scale to all AR objects relative to the webar-face and webar-face-pivot entities.

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

ParameterTypeDescription

pathURL

string

Path of json file created using lottie animations

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

ParameterTypeDescription

callbackFunction(markerId)

function

Callback function with markerId as argument that gets called when a marker image is detected and its corresponding 3D object appears.

markerId - Id of the currently detected marker image.

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

ParameterTypeDescription

callbackFunction(markerId)

function

Callback function with markerId as argument that gets called when a marker is lost

markerId - ID of the lost marker image.

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

ParameterTypeDescription

fillMouthArea

boolean

false - Mouth area appears hollow.

true - Mouth area appears filled.

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

ParameterTypeDescription

callbackFunction

function

Callback function that gets called when the mobile device approaches a 3d object.

closenessRatio

float

Specifies the object closeness threshold required to trigger this callback.

  • 0.25 to 0.4 represent a range of typical values depending on application.

  • 0.25 is closer than 0.4 .

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

ParameterTypeDescription

callbackFunction

function

Callback function that gets called when the reset button is clicked.

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

ParameterTypeDescription

isVisible

boolean

Determines the visibility of the reset button. Pass true to show the button or false to hide it.

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

ParameterTypeDescription

callbackFunction(markerId)

function

Callback function with markerId as argument that gets called when the 3d object appears for the first time on screen after the surface has been detected.

markerId - Id of the currently detected marker image.

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

ParameterTypeDescription

callbackFunction(trackingQuality)

function

Callback function with trackingQuality as an argument that gets called whenever tracking quality gets changed.

trackingQuality - quality of tracking:

  1. LOW

  2. MEDIUM

  3. HIGH

  4. LOST

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

ParameterDescription

callbackFunction()

function

Callback function is called when tracking has started

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

ParameterTypeDescription

callbackFunction()

function

Callback function is called when tracking has stopped

Returns

-

Example

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

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

Parameter

trackingMode

string

Two tracking modes are available, anyone can be passed as an argument:

  1. surface-tracking

  2. marker-tracking

Returns

-

Example

WEBARSDK.SetWebARMode(trackingMode);

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

ParameterTypeDescription

keepARAfterLost

boolean

By keeping this flag to true, AR object remains visible when tracking is lost. By default, flag value is kept to false.

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

ParameterTypeDescription

keepARVisible

boolean

By keeping this flag true, AR object remains visible when tracking is stopped. By default, flag value is kept false.

Returns

-

Example

WEBARSDK.StopTracking(true);

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

ParameterTypeDescription

callback

function

The callback is called after a snapshot is ready. It provides the canvas instance as an argument in which the screenshot buffer is drawn using its '2d' context. Example: (canvas) => { }

canvas

HTML Canvas Element

Instance of a HTML canvas element. The captured sanpshot is drawn on the 2d context of this user given canvas and also passed as an argument in the callback(1st parameter). If this parameter is ignored or null or undefined, then sdk creates a canvas element to draw the snapshot in 2d context and passes it to the callback(1st parameter).

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>

Last updated