ALL EXAMPLES ASSUME USAGE FROM CDN. IF USING FROM NPM, REMOVE MxtWebAR. PREFIX FROM ALL CLASS CALLS

Note also, that all examples are functions… don't forget to actually call these functions! Also, feel free to have these outside of functions, in your functions, or whatever you want to do!

Checking if an SKU has a WebAR asset

It is usually a good idea to use this call before using getWebArPregeneratedUrl as it is faster, and the manifest is used to determine if the webAR asset exists in browser cached for one hour.

So, for example, if you are using WebAR assets on your PDP pages, as customers go between different PDP pages, the manifest will get browser cached and calls to getAssetTypesAvailable should be lightning fast.

In the example below, make sure that you replace myApiKey and myClientId with your own, as provided by your Account Director.

async function checkForWebArAsset(sku) {
    const browserArType = MxtWebAR.MxtWebArHelpers.browserArSupport();
    const pregenerated = new MxtWebAR.MxtWebArPregenerated({apiKey:'myApiKey', clientId:'myClientId'});
    try {
      const arAssetsAvailable = await pregenerated.getAssetTypesAvailable(sku);
      if(!browserArType) {
          //CANT USE WEB AR IN THIS BROWSER, if there are arAssetsAvailable, make a QR code to direct the user to the redirect page. 
      }
      else if(arAssetsAvailable.includes(browserArType)) {
          //Web AR Assets are available and work in this browser!
      }
      else {
          //Web AR Assets would work in this browser, but we don't have any!
      }
    } catch(e) {
        console.error('Failed to check if sku has web ar asset', e);
    }
}

Adding the WebAR Asset to an <a> element as the HREF

After checking that the SKU has a WebAR asset, you can get the WebAR asset by doing this.

In the example below, make sure that you replace myApiKey and myClientId with your own, as provided by your Account Director.

async function addHrefToAnchorTag(anchorElement, sku) {
  try {
      const pregenerated = new MxtWebAR.MxtWebArPregenerated({apiKey:'myApiKey', clientId:'myClientId'});
      const url = await pregenerated.getWebArPregeneratedUrl(sku);
      anchorElement.href = url;
  } catch(e) {
      console.error('Failed to get sku web ar asset', e);
      return false;
  }
}

For iOS - THIS IS VERY IMPORTANT - PLEASE READ

iOS has some bizarreness in recognizing URLs on href tags as WebAR assets, especially inside in-app browsers. Marxent found that using this code will remedy that bizarre behavior:

<a rel="ar" id="view-in-ar" href="theUrlToWebArAsset">
  <img src="">
  <span>Launch AR</span>
</a>

If you want to deploy directly to your website or a test page, you can simply import this code in a <script> tag (make changes to suit your environment).

NOTE: <insert your WebAR Asset URL> is easily obtained by using the getWebArPregeneratedUrl method. Documented here: https://marxent.atlassian.net/wiki/spaces/3CMP/pages/2435252370/Details+of+the+WebAR+Asset+API+SDK#MxtWebArPregenerated

<script>
    const viewInRoomButton = document.getElementById("view-in-ar");
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onload = function() {  
            if (xmlhttp.status >= 200 && xmlhttp.status < 400) {
                viewInRoomButton.innerHTML = "View in Room";
                viewInRoomButton.href = xmlhttp.responseText;
                document.getElementsByTagName("body")[0].insertBefore(viewInRoomButton, document.getElementsByTagName("body")[0].firstChild);              
            }
        };
        var _isAndoidDevice = false; 
        // Device detection
        const detect = navigator.userAgent || navigator.vendor || window.opera;
        const ua = 'android';
        if (detect.toLowerCase().indexOf(ua) > -1) {
            _isAndoidDevice = true;
        }
        const isIOS = !!navigator.platform.match(/iP(ad|hone|od)/i);
        if (isIOS) {
            xmlhttp.open("GET", <insert your WebAR Asset URL>, true);
            xmlhttp.send();
        }
    }
</script>

Getting the GLB Model of an Asset

This is the code to get the GLB file (using this option has no formatting for opening as a WebAR asset in the browser).

async function getGlbModel(sku) {
  try {
      const pregenerated = new MxtWebAR.MxtWebArPregenerated({apiKey:'myApiKey', clientId:'myClientId'});
      const url = await pregenerated.getGlb(sku);
      return url;
  } catch(e) {
      console.error('Failed to get sku web ar asset', e);
      return false;
  }
}

Getting an Asset from a Particular Environment

By default, the SDK defaults to the PRODUCTION (live) environment. To get something from the TEST or STAGING environment, provide an additional option to the constructor like so:

const pregenerated = new MxtWebAR.MxtWebArPregenerated({apiKey:'myApiKey', clientId:'myClientId', serviceEnvironment:MxtWebAR.MxtAssetEnvironment.STAGING});  

Getting an Asset of a Particular State

By default, the SDK defaults to the PRODUCTION (live) state of an asset. To get the TEST or STAGING state, provide an additional option to the constructor like so:

const pregenerated = new MxtWebAR.MxtWebArPregenerated({apiKey:'myApiKey', clientId:'myClientId', assetEnvironment:MxtWebAR.MxtAssetEnvironment.STAGING});  

Getting an Asset of a Particular LOD (level of detail)

Assets default to 512x512 pixel textures if no LOD is provided. To provide a specific LOD, use:

const url = await pregenerated.getWebArPregeneratedUrl(sku, LOD._1024);

OR

const url = await pregenerated.getGlb(sku, LOD._1024);

Launching a Product from a QR Code

Although spins of a GLB asset are possible on desktop, launching into AR is only supported on Mobile.

It is a common path therefore on desktop, to show a “View in AR” capability, but have it show a QR code to scan on a mobile device.

Creating a QR Code

Here is an example of this using the QRious library, though any QR Code library will do.

<div id="qr-modal" class="modal" style="display:none;" >
   <div class="modal-content">
      <div class="close">&times;</div>
      <h3>Viewing your products in AR</h3>
      <p class="subtext">Scan this QR code with your mobile device's camera to view this product in AR.</p>
      <div id="qr-url"></div>
      <canvas id="qr" class="qr"></canvas>
   </div>
</div>
<script>
   var qr = new QRious({
       size: 500,
       element: document.getElementById('qr'),
   // Remember to make sure the value for the QR code url is absolute, not relative, since the QR will be generated based on this text.
   // This should direct to the location of the "AR Launch page" detailed below in the documentation
       value: "https://exampledomain.com/demo/web-ar/sdk-qr.html" + "?sku=" + sku + "&lod=" + lod
   });
</script>

AR Launch Page

This is an example of a page to be written onto your domain. This is the page that will launch of a phone that can in turn launch AR immediately to the user.

This technique gives you a handle for doing any in between steps since this is the first moment launching onto a user’s device.

<html><head>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <link rel="icon" type="image/x-icon" href="https://cms.3dcloud.io/assets/images/favicon.ico">
    <link rel="stylesheet" media="screen" href="css/style.css">
    <script src="https://cdn.3dcloud.io/mxt-ar-sdk/7.5.0/MxtWebAR-#.#.#.min.js"></script>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async="" src="https://www.googletagmanager.com/gtag/js?id=G-211KTZXPL6"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
    
      gtag('config', 'G-211KTZXPL6');
    </script>
</head>

<body>
  <div id="loading" style="display: block; margin: 20vh 20vw; text-align: center;">This product is not yet available in AR.  Please try a different product.</div>
  <a href="#" id="mainButton" style="display:none;" class="btn" rel="ar"><img src="" width="0" height="0">View In Your Home</a>

  <script type="text/javascript">
        const urlParams = new URLSearchParams(window.location.search);
        const sku = urlParams.get('sku');
        const anchorElement = document.getElementById('mainButton');
        
        const myApiKey = myApiKey
        const myClientId = myClientId
        
        // Get the approproate AR asset for the user's device and redirect the browser to that file.
        async function launchAr() {
            try {
                const pregenerated = new MxtWebAR.MxtWebArPregenerated({apiKey: myApiKey, clientId: myClientId });
                const url = await pregenerated.getWebArPregeneratedUrl(sku);
            // Set the AR button href to the AR file url
                document.getElementById("mainButton").href = url
            // Simulate click of the AR button to launch directly into AR.  IMPORTANT - This step prevents iOS from taking a user to the placeholder image/poster.  
            // This provides the best user experience from a QR code
                document.getElementById("mainButton").click();
            } catch(e) {
                console.error('Failed to get sku web ar asset', e);
                document.getElementById("loading").innerHTML = "This product is not yet available in AR.  Please try a different product."
                return false;
            }
        }
        launchAr();
  </script>


</body></html>