### Marker Based AR.js Example with A-Frame Source: https://ar-js-org.github.io/AR.js-Docs/index This example shows how to implement marker-based augmented reality using AR.js and A-Frame. It sets up a scene where a 3D model (a glTF model of a T-Rex) is displayed when the 'hiro' marker is detected by the camera. Essential A-Frame and AR.js libraries are included. ```html ``` -------------------------------- ### AR.js Setup with npm and Webpack Source: https://ar-js-org.github.io/AR.js-Docs/location-based Instructions for setting up AR.js in an application using npm. This includes a sample package.json for dependencies and scripts, and a webpack.config.js for bundling the application. The output bundle is named 'bundle.js'. ```json { "dependencies": { "@ar-js-org/ar.js": "3.4.7" }, "devDependencies": { "webpack": "^5.75.0", "webpack-cli": "^5.0.0" }, "scripts": { "build": "npx webpack" } } ``` ```javascript const path = require('path'); module.exports = { mode: 'development', entry: './index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js' }, optimization: { minimize: false } }; ``` ```javascript import * as THREEx from './node_modules/@ar-js-org/ar.js/three.js/build/ar-threex-location-only.js' ``` -------------------------------- ### AR.js Image Tracking Setup with A-Frame Source: https://ar-js-org.github.io/AR.js-Docs/image-tracking This HTML snippet demonstrates the basic setup for AR.js image tracking using A-Frame. It includes importing necessary A-Frame and AR.js scripts, defining a basic loader, and configuring an `a-scene` with an `a-nft` component. The `a-nft` component is configured with the path to your generated image descriptors and specifies the content (a GLTF model) to be rendered when the image is detected. ```html AR.js Image Tracking
Loading, please wait...
``` -------------------------------- ### Location Based AR.js Example with A-Frame Source: https://ar-js-org.github.io/AR.js-Docs/index This example demonstrates how to create a location-based AR experience using AR.js and A-Frame. It requires user's GPS coordinates to place a red box in the augmented reality view. The code includes necessary A-Frame and AR.js scripts and configures a camera with GPS capabilities. ```html AR.js A-Frame Location-based ``` -------------------------------- ### AR.js Image Tracking Example with A-Frame Source: https://ar-js-org.github.io/AR.js-Docs/index This snippet demonstrates how to set up an AR.js scene for image tracking using A-Frame. It includes necessary script imports for A-Frame and AR.js, basic styling for a loader, and the HTML structure for an AR scene with an NFT marker and a 3D model. Ensure you run this on a server with a secure connection (HTTPS) and have compatible versions of AR.js and A-Frame. ```html
Loading, please wait...
``` -------------------------------- ### Import Location-based AR.js with A-Frame Source: https://ar-js-org.github.io/AR.js-Docs/index This setup imports A-Frame, the AR.js library for location-based tracking (using three.js internally), and the AR.js A-Frame components. It's recommended to use a specific stable version like 3.4.7 for iOS compatibility. ```html
``` -------------------------------- ### Trigger Actions on Marker Found with JavaScript and A-Frame Source: https://ar-js-org.github.io/AR.js-Docs/ui-events This snippet demonstrates how to attach a custom A-Frame component ('markerhandler') that listens for the 'markerFound' event. When the event is triggered, it redirects the user to a specified URL. It includes necessary AR.js and A-Frame scripts, basic CSS for a loader, and an A-Frame scene setup with an NFT marker. ```html
Loading, please wait...
``` -------------------------------- ### THREEx.ArtoolkitContext Parameters Source: https://ar-js-org.github.io/AR.js-Docs/marker-based Configuration parameters for initializing the ARToolKit context. ```APIDOC ## THREEx.ArtoolkitContext ### Description Provides configuration parameters for initializing the ARToolKit context, including detection modes, matrix types, and camera parameters. ### Method N/A (Configuration Object) ### Endpoint N/A ### Parameters #### Initialization Parameters - **debug** (boolean) - Optional - If true, displays the ARToolKit debug canvas. - **detectionMode** (string) - Optional - The mode of detection. Valid values: 'color', 'color_and_matrix', 'mono', 'mono_and_matrix'. Defaults to 'color_and_matrix'. - **matrixCodeType** (string) - Optional - The type of matrix code. Valid if detectionMode ends with 'matrix'. Examples: '3x3', '3x3_HAMMING63', '3x3_PARITY65', '4x4', '4x4_BCH_13_9_3', '4x4_BCH_13_5_5'. Defaults to '3x3'. - **patternRatio** (number) - Optional - Pattern ratio for custom markers. Defaults to 0.5. - **labelingMode** (string) - Optional - Labeling mode for markers. Valid values: 'black_region', 'white_region'. Defaults to 'black_region'. - **cameraParametersUrl** (string) - Required - URL of the camera parameters file (e.g., 'camera_para.dat'). - **maxDetectionRate** (integer) - Optional - The maximum rate of pose detection in the source image. Defaults to 60. - **canvasWidth** (integer) - Optional - The resolution width at which pose is detected in the source image. Defaults to 640. - **canvasHeight** (integer) - Optional - The resolution height at which pose is detected in the source image. Defaults to 480. - **imageSmoothingEnabled** (boolean) - Optional - Enables or disables image smoothing for canvas copy. Defaults to true. ### Request Example ```json { "debug": false, "detectionMode": "color_and_matrix", "matrixCodeType": "3x3", "patternRatio": 0.5, "labelingMode": "black_region", "cameraParametersUrl": "../data/data/camera_para.dat", "maxDetectionRate": 60, "canvasWidth": 640, "canvasHeight": 480, "imageSmoothingEnabled": true } ``` ### Response N/A (This is a configuration object for initialization.) ``` -------------------------------- ### Basic HTML for Location-Based AR Scene with A-Frame Source: https://ar-js-org.github.io/AR.js-Docs/location-based-aframe This HTML code sets up a basic Augmented Reality scene using A-Frame and AR.js for location-based experiences. It includes necessary scripts for A-Frame and AR.js, defines a camera with GPS capabilities, and places a simple red box at a specified latitude and longitude. Ensure you replace placeholder coordinates with actual values and host the page on a server with HTTPS or run it locally on localhost. ```html AR.js A-Frame Location-based ``` -------------------------------- ### Calculate Marker Distance with AR.js Source: https://ar-js-org.github.io/AR.js-Docs/ui-events This JavaScript code calculates the distance between the camera and an AR.js marker. It attaches event listeners to the 'markerFound' and 'markerLost' events of an 'a-marker' element. When the marker is found, it starts an interval to continuously log the distance between the camera and marker positions. The interval is cleared when the marker is lost. ```javascript // import this on your HTML window.addEventListener('load', () => { const camera = document.querySelector('[camera]'); const marker = document.querySelector('a-marker'); let check; marker.addEventListener('markerFound', () => { let cameraPosition = camera.object3D.position; let markerPosition = marker.object3D.position; let distance = cameraPosition.distanceTo(markerPosition) check = setInterval(() => { cameraPosition = camera.object3D.position; markerPosition = marker.object3D.position; distance = cameraPosition.distanceTo(markerPosition) // do what you want with the distance: console.log(distance); }, 100); }); marker.addEventListener('markerLost', () => { clearInterval(check); }) }) ``` -------------------------------- ### THREEx.ArtoolkitSource Parameters Source: https://ar-js-org.github.io/AR.js-Docs/marker-based Configuration parameters for initializing the ARToolKit source. ```APIDOC ## THREEx.ArtoolkitSource ### Description Provides configuration parameters for initializing the ARToolKit source, allowing selection between webcam, image, or video inputs. ### Method N/A (Configuration Object) ### Endpoint N/A ### Parameters #### Initialization Parameters - **sourceType** (string) - Required - The type of source. Valid values: 'webcam', 'image', 'video'. - **sourceUrl** (string) - Optional - The URL of the source. Valid if sourceType is 'image' or 'video'. Defaults to null. - **sourceWidth** (integer) - Optional - The resolution width at which the source image is initialized. Defaults to 640. - **sourceHeight** (integer) - Optional - The resolution height at which the source image is initialized. Defaults to 480. - **displayWidth** (integer) - Optional - The resolution width at which the source image is displayed. Defaults to 640. - **displayHeight** (integer) - Optional - The resolution height at which the source image is displayed. Defaults to 480. ### Request Example ```json { "sourceType": "webcam", "sourceUrl": null, "sourceWidth": 640, "sourceHeight": 480, "displayWidth": 640, "displayHeight": 480 } ``` ### Response N/A (This is a configuration object for initialization.) ``` -------------------------------- ### Import AR.js for NFT Image Tracking (three.js) Source: https://ar-js-org.github.io/AR.js-Docs/index This script tag imports the pure three.js version of AR.js, optimized for NFT (markerless) image tracking. This is suitable for projects not using A-Frame. ```html ``` -------------------------------- ### Import AR.js for Marker Tracking (A-Frame) Source: https://ar-js-org.github.io/AR.js-Docs/index This script tag imports the A-Frame version of AR.js for traditional marker-based tracking. It allows AR content to be anchored to specific image markers. ```html ``` -------------------------------- ### Listen for AR.js NFT Loaded Event Source: https://ar-js-org.github.io/AR.js-Docs/image-tracking This JavaScript snippet shows how to add an event listener for the 'arjs-nft-loaded' event. This event fires when all NFT markers have finished loading, signaling that marker tracking can begin. It's useful for managing loading states in your application. ```javascript window.addEventListener("arjs-nft-loaded", (event) => { // Hide loading overlay }); ``` -------------------------------- ### Reduce Shaking with Classic/Projected Components (HTML) Source: https://ar-js-org.github.io/AR.js-Docs/location-based This snippet demonstrates how to reduce shaking effects in AR.js location-based mode using the `arjs-look-controls` component with exponential smoothing. This is for users of classic and projected location-based components. The `smoothingFactor` property adjusts the smoothing level; a lower value results in greater smoothing. ```html ``` -------------------------------- ### Location-Based Content with `gps-new-camera` and `gps-projected-camera` Source: https://ar-js-org.github.io/AR.js-Docs/location-based These components allow you to overlay augmented reality content based on real-world geographic coordinates. They utilize the `latLonToWorld` method to convert latitude and longitude into world coordinates suitable for AR.js. ```APIDOC ## Calculating world coordinates of arbitrary augmented content The `new-location-based` and `projected` components have some useful properties and methods which can be used to easily work with more specialist augmented content (for example, you might want to overlay AR polylines or polygons representing roads and paths, downloaded from geodata APIs such as OpenStreetMap). Such data can be downloaded from the API as lat/lon based coordinates, projected using AR.js API methods into Spherical Mercator (approximating to, but not exactly metres, but in tests good enough to use as world coordinates), and then added to the scene as a three.js object. This is implemented differently in the `new-location-based` and `projected` components, but the external API is (as of 3.4.3) the same. The key method is the `latLonToWorld(lat, lon)` method of the `gps-new-camera` and `gps-projected-camera` components. This converts latitude and longitude directly to world coordinates, performing the projection as the first step and then calculating the world coordinates from the projected coordinates. It will return a 2-member array containing the _x_ and _z_ world coordinates, allowing the developer to calculate or specify the _y_ coordinate (altitude) independently. Note that the sign of the Spherical Mercator northing is reversed to align with the OpenGL coordinate system (eastings are equivalent to `x` coordinates and northings to `z` coordinates). `gps-new-camera` implements projection via the underlying AR.js three.js `LocationBased` object (see three.js documentation, below) which is responsible for the actual projection. `gps-projected-camera` provides similar functionality but via a different method and with some implementation differences. In `gps-projected-camera`, unlike `gps-new-camera`, the **original GPS position** is set as the world origin. ``` -------------------------------- ### Add GPS-Based Entity with JavaScript in AR.js Source: https://ar-js-org.github.io/AR.js-Docs/location-based-aframe This JavaScript code snippet demonstrates how to retrieve the user's GPS location and dynamically add a red box entity to the AR scene. It listens for the 'gps-camera-update-position' event and places the entity north of the initial GPS fix. Dependencies include A-Frame and AR.js. ```javascript window.onload = () => { let testEntityAdded = false; const el = document.querySelector("[gps-new-camera]"); el.addEventListener("gps-camera-update-position", e => { if(!testEntityAdded) { alert(`Got first GPS position: lon ${e.detail.position.longitude} lat ${e.detail.position.latitude}`); // Add a box to the north of the initial GPS position const entity = document.createElement("a-box"); entity.setAttribute("scale", { x: 20, y: 20, z: 20 }); entity.setAttribute('material', { color: 'red' } ); entity.setAttribute('gps-new-entity-place', { latitude: e.detail.position.latitude + 0.001, longitude: e.detail.position.longitude }); document.querySelector("a-scene").appendChild(entity); } testEntityAdded = true; }); }; ``` -------------------------------- ### Enable Webcam Texture for Distant Objects in AR.js Source: https://ar-js-org.github.io/AR.js-Docs/location-based This snippet demonstrates how to configure the AR.js system to use a webcam texture for viewing distant augmented reality content. Setting `videoTexture` to `true` and `sourceType` to `webcam` automatically injects the `arjs-webcam-texture` component. ```html ```