### Basic 'Hello World' with AR.js
Source: https://github.com/ar-js-org/ar.js/blob/master/aframe/examples/location-based/README.md
A simple HTML-only example showing a box at a specific GPS coordinate relative to the user's location. Useful for a quick start.
```html
```
--------------------------------
### Multiple Boxes Example
Source: https://github.com/ar-js-org/ar.js/blob/master/aframe/examples/location-based/README.md
Extends the 'hello-world' example by displaying four boxes positioned north, south, east, and west of the user's current location. Demonstrates basic multi-object placement.
```html
```
--------------------------------
### Setup Rendering and Stats
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/default.html
Appends performance statistics to the document body and sets up the rendering loop to display the scene.
```javascript
var stats = new Stats();
document.body.appendChild(stats.dom);
onRenderFcts.push(function () {
renderer.render(scene, camera);
stats.update();
})
```
--------------------------------
### Show Distance to Object Example
Source: https://github.com/ar-js-org/ar.js/blob/master/aframe/examples/location-based/README.md
An enhanced 'basic-js' example that displays the distance to an object when it is clicked. This requires implementing click handling and distance calculation logic.
```javascript
AFRAME.registerComponent('show-distance', {
init: function () {
const scene = this.el;
// ... (logic to create boxes)
const box = document.createElement('a-box');
// ... (set attributes)
scene.appendChild(box);
box.addEventListener('click', function() {
const distance = calculateDistance(box.object3D.position, scene.camera.position);
console.log('Distance:', distance);
// Display distance on screen or in console
});
}
});
function calculateDistance(pos1, pos2) {
// Implementation for distance calculation
return Math.sqrt(Math.pow(pos1.x - pos2.x, 2) + Math.pow(pos1.y - pos2.y, 2) + Math.pow(pos1.z - pos2.z, 2));
}
```
--------------------------------
### Initialize ARToolKit Context
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/multi-markers/examples/tmp/learner-old.html
Sets up the ARToolKit context with camera parameters and detection settings. `detectionMode: 'mono'` is used for single-camera setups.
```javascript
var arToolkitContext = new THREEx.ArToolkitContext({
cameraParametersUrl: THREEx.ArToolkitContext.baseURL + '../data/data/camera_para.dat',
detectionMode: 'mono',
maxDetectionRate: 30,
// high accuracy of detection on purpose - important during learning
// canvasWidth: 80*4,
// canvasHeight: 60*4,
// debug: true,
})
// initialize it
arToolkitContext.init(function onCompleted(){
// copy projection matrix to camera
camera.projectionMatrix.copy( arToolkitContext.getProjectionMatrix() );
})
```
--------------------------------
### Setup Performance Stats and Render Loop
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/marker-training/examples/patternmarker-from-image.html
Initializes performance statistics display and sets up the main rendering loop. The loop measures time delta and calls all registered update functions.
```javascript
var stats = new Stats();
document.body.appendChild( stats.dom );
```
```javascript
// render the scene
onRenderFcts.push(function(){
renderer.render( scene, camera );
stats.update();
})
```
```javascript
// run the rendering loop
var lastTimeMsec= null
requestAnimationFrame(function animate(nowMsec){
// keep looping
equestAnimationFrame( animate );
// measure time
lastTimeMsec = lastTimeMsec || nowMsec-1000/60
var deltaMsec = Math.min(200, nowMsec - lastTimeMsec)
lastTimeMsec = nowMsec
// call each update function
onRenderFcts.forEach(function(onRenderFct){
onRenderFct(deltaMsec/1000, nowMsec/1000)
})
})
```
--------------------------------
### npm Package Installation
Source: https://context7.com/ar-js-org/ar.js/llms.txt
Install AR.js using npm or yarn for use in JavaScript projects.
```bash
# Install with npm
npm install @ar-js-org/ar.js
# Install with yarn
yarn add @ar-js-org/ar.js
```
--------------------------------
### Install npm Packages for Tests
Source: https://github.com/ar-js-org/ar.js/blob/master/test/README.md
Run this command in your terminal to install all necessary npm packages for the AR.js tests. Ensure you are in the project's root directory.
```bash
npm install
```
--------------------------------
### Setup Performance Statistics and Render Loop
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/mobile-performance.html
Initializes performance statistics display and sets up the main animation loop using requestAnimationFrame. This includes rendering the scene and updating stats.
```javascript
var stats = new Stats();
document.body.appendChild(stats.dom);
onRenderFcts.push(function () {
renderer.render(scene, camera);
stats.update();
})
var lastTimeMsec = null
requestAnimationFrame(function animate(nowMsec) {
requestAnimationFrame(animate);
var deltaMsec = Math.min(200, nowMsec - lastTimeMsec)
lastTimeMsec = nowMsec
onRenderFcts.forEach(function (onRenderFct) {
onRenderFct(deltaMsec / 1000, nowMsec / 1000)
})
})
```
--------------------------------
### Main Rendering Loop Setup
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/multi-markers/examples/player.html
Sets up the main rendering loop using requestAnimationFrame. It measures time delta, updates all registered render functions, and renders the scene. Includes optional stats.dom for performance monitoring.
```javascript
var stats = new Stats();
// document.body.appendChild( stats.dom );
// render the scene
onRenderFcts.push(function(delta){
renderer.render( scene, camera );
stats.update();
})
// run the rendering loop
var lastTimeMsec= null
requestAnimationFrame(function animate(nowMsec){
// keep looping
requestAnimationFrame( animate );
// measure time
lastTimeMsec = lastTimeMsec || nowMsec-1000/60
var deltaMsec = Math.min(200, nowMsec - lastTimeMsec)
lastTimeMsec = nowMsec
// call each update function
onRenderFcts.forEach(function(onRenderFct){
onRenderFct(deltaMsec/1000, nowMsec/1000)
})
})
```
--------------------------------
### Start Multi-Marker Recording
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/multi-markers/examples/learner-testrunner.html
Starts the multi-marker learning process by enabling data collection. This function prevents starting if already enabled and resets previous statistics.
```javascript
function onRecordStart(){
// cant be started, if it is already started
if( multiMarkerLearning.enabled === true ){
console.log('already started')
return
}
// reset previously collected statistics
multiMarkerLearning.resetStats()
// enabled data collection
multiMarkerLearning.enabled = true
// update application status
updateAppStatus()
}
```
--------------------------------
### Install AR.js with npm
Source: https://github.com/ar-js-org/ar.js/blob/master/README.md
Use this command to install the AR.js package in your project if you are using a build system that supports npm modules like React.js or Vue.js.
```bash
npm install @ar-js-org/ar.js
```
--------------------------------
### Render OSM Ways (Roads/Paths) Example
Source: https://github.com/ar-js-org/ar.js/blob/master/aframe/examples/location-based/README.md
A complex example for rendering specialized geodata like OpenStreetMap ways (roads, paths). It downloads data from a GeoJSON API, reprojects it to Spherical Mercator, and renders it as polylines.
```javascript
AFRAME.registerComponent('osm-ways', {
init: function () {
const scene = this.el;
const osmWaysUrl = 'YOUR_OSM_WAYS_GEOJSON_URL'; // Replace with actual URL
fetch(osmWaysUrl)
.then(response => response.json())
.then(data => {
data.features.forEach(feature => {
if (feature.geometry.type === 'LineString') {
const latLngs = feature.geometry.coordinates;
// Reproject lat/lng to Spherical Mercator and create A-Frame geometry
const vertices = latLngs.map(ll => {
const mercator = latLngToMercator(ll[1], ll[0]);
return `${mercator.x} 0 ${mercator.y}`;
}).join('\n');
const polyline = document.createElement('a-entity');
polyline.setAttribute('geometry', `primitive: polyline; vertices: ${vertices}; color: white;`);
scene.appendChild(polyline);
}
});
});
}
});
function latLngToMercator(lat, lng) {
// Spherical Mercator projection implementation
const R = 6378137;
const x = R * (lng * Math.PI / 180);
const y = R * Math.log(Math.tan((90 + lat) * Math.PI / 360));
return { x, y };
}
```
--------------------------------
### A-Frame Marker-Based AR Example
Source: https://context7.com/ar-js-org/ar.js/llms.txt
Demonstrates AR.js marker-based tracking with A-Frame. Includes examples for preset 'hiro' markers, custom pattern files, and barcode markers. Ensure AR.js is included via a script tag.
```html
```
--------------------------------
### Install AR.js via npm or yarn
Source: https://context7.com/ar-js-org/ar.js/llms.txt
Install the AR.js package using either npm or yarn. This is the first step for integrating AR.js into your project.
```bash
npm install @ar-js-org/ar.js
```
```bash
yarn add @ar-js-org/ar.js
```
--------------------------------
### Three.js Scene and Camera Setup
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/multi-markers/examples/learner.html
Initializes a Three.js scene and a basic camera. The camera's projection matrix will be updated by AR.js.
```javascript
var scene = new THREE.Scene();
// Create a camera
if( urlOptions.trackingBackend === 'artoolkit' ){
var camera = new THREE.Camera();
}else console.assert(false)
scene.add(camera);
```
--------------------------------
### Clickable AR Objects Example
Source: https://github.com/ar-js-org/ar.js/blob/master/aframe/examples/location-based/README.md
Demonstrates adding click event listeners to AR objects. This example leverages A-Frame's 'cursor' and 'raycaster' components for interaction. Ensure these components are available.
```html
```
--------------------------------
### Install AR.js with yarn
Source: https://github.com/ar-js-org/ar.js/blob/master/README.md
Use this command to install the AR.js package in your project if you are using yarn as your package manager.
```bash
yarn add @ar-js-org/ar.js
```
--------------------------------
### Start Multi-Marker Recording
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/multi-markers/examples/learner.html
Starts the data collection for multi-marker learning. It checks if recording is already enabled and resets previous statistics before enabling collection.
```javascript
function onRecordStart(){
// cant be started, if it is already started
if( multiMarkerLearning.enabled === true ){
console.log('already started')
return
}
// reset previously collected statistics
multiMarkerLearning.resetStats()
// enabled data collection
multiMarkerLearning.enabled = true
// update application status
updateAppStatus()
}
```
--------------------------------
### Download and Display POIs Example
Source: https://github.com/ar-js-org/ar.js/blob/master/aframe/examples/location-based/README.md
Demonstrates fetching Points of Interest (POIs) from an OpenStreetMap-based GeoJSON API and rendering them as objects with text labels in the AR scene. Requires a GeoJSON API endpoint.
```javascript
AFRAME.registerComponent('poi', {
init: function () {
const scene = this.el;
const geojsonUrl = 'YOUR_GEOJSON_API_URL'; // Replace with actual URL
fetch(geojsonUrl)
.then(response => response.json())
.then(data => {
data.features.forEach(feature => {
const coords = feature.geometry.coordinates;
const name = feature.properties.name || 'POI';
const entity = document.createElement('a-entity');
entity.setAttribute('gps-new-entity-place', `latitude: ${coords[1]}; longitude: ${coords[0]};
`);
entity.setAttribute('material', 'color', 'red');
entity.setAttribute('geometry', 'primitive: sphere; radius: 10');
const label = document.createElement('a-entity');
label.setAttribute('position', '0 1 0');
label.setAttribute('text', `value: ${name}; align: center; width: 50;`);
entity.appendChild(label);
scene.appendChild(entity);
});
});
}
});
```
--------------------------------
### Basic JavaScript AR.js Example
Source: https://github.com/ar-js-org/ar.js/blob/master/aframe/examples/location-based/README.md
A fundamental JavaScript example that dynamically generates four boxes (north, south, east, west) based on an initial GPS position. Supports desktop testing with a fake latitude/longitude.
```javascript
AFRAME.registerComponent('basic-js', {
init: function () {
const scene = this.el;
const positions = [
{ x: 0, y: 1.5, z: -5 }, // North
{ x: 0, y: 1.5, z: -15 }, // South
{ x: 10, y: 1.5, z: -10 }, // East
{ x: -10, y: 1.5, z: -10 } // West
];
const colors = ['red', 'blue', 'green', 'orange'];
positions.forEach((pos, index) => {
const box = document.createElement('a-box');
box.setAttribute('position', `${pos.x} ${pos.y} ${pos.z}`);
box.setAttribute('rotation', '0 45 0');
box.setAttribute('color', colors[index]);
scene.appendChild(box);
});
}
});
```
--------------------------------
### A-Frame Image Tracking (NFT) Example
Source: https://context7.com/ar-js-org/ar.js/llms.txt
Implements Natural Feature Tracking (NFT) for AR.js using A-Frame. This example tracks a specific image using pre-computed descriptors and anchors a 3D model. Requires the 'aframe-ar-nft.js' script.
```html
```
--------------------------------
### Initialize AR Toolkit Source (Webcam)
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/dev.html
Initializes the AR.js source to read from the webcam. Includes event listeners for 'canplay' to start AR context initialization and handles window resizing.
```javascript
var arToolkitSource = new ArToolkitSource({
// to read from the webcam
sourceType: 'webcam',
//
// to read from an image
// sourceType : 'image',
// sourceUrl : THREEx.ArToolkitContext.baseURL + '../data/images/img.jpg',
// sourceUrl : THREEx.ArToolkitContext.baseURL + '../data/images/armchair.jpg',
// to read from a video
// sourceType : 'video',
// sourceUrl : THREEx.ArToolkitContext.baseURL + '../data/videos/headtracking.mp4',
})
arToolkitSource.init(() => {
arToolkitSource.domElement.addEventListener('canplay', () => {
console.log(
'canplay',
'actual source dimensions',
arToolkitSource.domElement.videoWidth,
arToolkitSource.domElement.videoHeight
);
initARContext();
});
window.arToolkitSource = arToolkitSource;
onResize();
});
// handle resize
window.addEventListener('resize', function () {
onResize()
})
```
--------------------------------
### A-Frame Location-Based AR Example
Source: https://context7.com/ar-js-org/ar.js/llms.txt
Sets up location-based AR using A-Frame components like 'gps-entity-place' and 'gps-camera'. This example places a red box and text at specific GPS coordinates, with the text always facing the user. Requires 'aframe-look-at-component.min.js' and 'aframe-ar-nft.js'.
```html
```
--------------------------------
### Three.js Location-Based AR Setup
Source: https://context7.com/ar-js-org/ar.js/llms.txt
Initializes a Three.js scene, webcam background, device orientation controls, and the LocationBased AR module. Requires Three.js and AR.js libraries.
```javascript
import * as THREE from 'three';
import { LocationBased, WebcamRenderer, DeviceOrientationControls } from '@ar-js-org/ar.js/three.js/build/ar-threex-location-only.js';
// Setup Three.js scene
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 10000);
const renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Initialize webcam background
const webcamRenderer = new WebcamRenderer(renderer);
// Initialize device orientation controls
const deviceControls = new DeviceOrientationControls(camera);
// Initialize location-based AR
const locationBased = new LocationBased(scene, camera, {
gpsMinDistance: 5, // Minimum GPS movement in meters to trigger update
gpsMinAccuracy: 100, // Maximum acceptable GPS accuracy in meters
maximumAge: 0, // Maximum age of GPS position in milliseconds
initialPositionAsOrigin: true // Use first GPS position as world origin
});
```
--------------------------------
### Custom Component for POI Display
Source: https://github.com/ar-js-org/ar.js/blob/master/aframe/examples/location-based/README.md
Similar to the 'poi' example, but showcases the implementation and usage of a custom A-Frame component for downloading and displaying POIs. This promotes code reusability.
```javascript
AFRAME.registerComponent('poi-component', {
dependencies: ['gps-new-entity-place'],
schema: {
geojsonUrl: {
type: 'string',
default: ''
}
},
init: function () {
const entity = this.el;
const geojsonUrl = this.data.geojsonUrl;
fetch(geojsonUrl)
.then(response => response.json())
.then(data => {
// ... (logic to process GeoJSON and create entities/labels)
// Example: create a simple marker
entity.setAttribute('material', 'color', 'blue');
entity.setAttribute('geometry', 'primitive: box; width: 20; height: 20; depth: 20');
});
}
});
```
--------------------------------
### Initialize AR.js with Webcam and Hiro Marker
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/default.html
This code initializes the AR.js context and source, setting up the webcam as input and configuring it to detect the 'hiro' pattern marker. It includes essential setup for the renderer, scene, and camera, and handles window resizing.
```javascript
import * as THREE from 'three'
import { ArToolkitProfile, ArToolkitSource, ArToolkitContext, ArMarkerControls } from 'threex'
ArToolkitContext.baseURL = '../'
////////////////////////////////////////////////////////////////////////////////
// Init
////////////////////////////////////////////////////////////////////////////////
// init renderer
var renderer = new THREE.WebGLRenderer({
// antialias : true,
alpha: true
});
renderer.setClearColor(new THREE.Color('lightgrey'), 0)
// renderer.setPixelRatio( 2 );
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.domElement.style.position = 'absolute'
renderer.domElement.style.top = '0px'
renderer.domElement.style.left = '0px'
document.body.appendChild(renderer.domElement);
// array of functions for the rendering loop
var onRenderFcts = [];
var arToolkitContext, arMarkerControls, markerGroup;
// init scene and camera
var scene = new THREE.Scene();
////////////////////////////////////////////////////////////////////////////////
// Initialize a basic camera
////////////////////////////////////////////////////////////////////////////////
// Create a camera
var camera = new THREE.Camera();
scene.add(camera)
markerGroup = new THREE.Group
scene.add(markerGroup)
//////////////////////////////////////////////////////////////////////////////
// handle arToolkitSource
//////////////////////////////////////////////////////////////////////////////
var artoolkitProfile = new ArToolkitProfile()
artoolkitProfile.sourceWebcam()
// artoolkitProfile.sourceVideo(THREEx.ArToolkitContext.baseURL + '../data/videos/headtracking.mp4').kanjiMarker();
// artoolkitProfile.sourceImage(THREEx.ArToolkitContext.baseURL + '../data/images/img.jpg').hiroMarker()
var arToolkitSource = new ArToolkitSource(artoolkitProfile.sourceParameters)
arToolkitSource.init(() => {
arToolkitSource.domElement.addEventListener('canplay', () => {
console.log('canplay', 'actual source dimensions', arToolkitSource.domElement.videoWidth, arToolkitSource.domElement.videoHeight);
initARContext();
});
window.arToolkitSource = arToolkitSource
onResize();
})
// handle resize
window.addEventListener('resize', function() {
onResize()
})
function onResize() {
arToolkitSource.onResizeElement()
arToolkitSource.copyElementSizeTo(renderer.domElement)
if (window.arToolkitContext.arController !== null) {
arToolkitSource.copyElementSizeTo(window.arToolkitContext.arController.canvas)
}
}
//////////////////////////////////////////////////////////////////////////////
// initialize arToolkitContext
//////////////////////////////////////////////////////////////////////////////
function initARContext() {
console.log('initARContext()');
// CONTEXT
arToolkitContext = new ArToolkitContext(artoolkitProfile.contextParameters)
arToolkitContext.init(() => {
camera.projectionMatrix.copy(arToolkitContext.getProjectionMatrix());
arToolkitContext.arController.orientation = getSourceOrientation();
arToolkitContext.arController.options.orientation = getSourceOrientation();
console.log('arToolkitContext', arToolkitContext);
window.arToolkitContext = arToolkitContext;
});
// MARKER
arMarkerControls = new ArMarkerControls(arToolkitContext, markerGroup, {
type: 'pattern',
patternUrl: ArToolkitContext.baseURL + '../data/data/patt.hiro',
})
console.log('ArMarkerControls', arMarkerControls);
window.arMarkerControls = arMarkerControls;
}
function getSourceOrientation() {
if (!arToolkitSource) {
return null;
}
console.log('actual source dimensions', arToolkitSource.domElement.videoWidth, arToolkitSource.domElement.videoHeight);
if (arToolkitSource.domElement.videoWidth > arToolkitSource.domElement.videoHeight) {
console.log('source orientation', 'landscape');
return 'landscape';
} else {
console.log('source orientation', 'portrait');
return 'portrait';
}
}
// update artoolkit on every frame
onRenderFcts.push(function() {
if (!arToolkitContext || !arToolkitSource || !arToolkitSource.ready) {
return;
}
arToolkitContext.update(arToolkitSource.domElement)
})
////////////////////////////////////////////////////////////////////////////////
// add an object in the scene
////////////////////////////////////////////////////////////////////////////////
var markerScene = new THREE.Scene()
markerGroup.add(markerScene)
var mesh = new THREE.AxesHelper()
markerScene.add(mesh)
// add a torus knot
var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshNormalMaterial({
transparent: true,
opacity: 0.5,
side: THREE.DoubleSide
});
var mesh = new THREE.Mesh(geometry, material);
mesh
```
--------------------------------
### AR.js Rendering Loop Setup
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/multi-markers/examples/learner-testrunner.html
Sets up the rendering loop for the AR.js scene. It includes initializing performance statistics and defining the animation function that calls all registered update functions.
```javascript
onRecordStart() ////////////////////////////////////////////////////////////////////////////////// // render the whole thing on the page //////////////////////////////////////////////////////////////////////////////////
var stats = new Stats();
// document.body.appendChild( stats.dom );
// render the scene
onRenderFcts.push(function(){
renderer.render( scene, camera );
stats.update();
})
// run the rendering loop
var lastTimeMsec= null
requestAnimationFrame(function animate(nowMsec){
// keep looping
requestAnimationFrame( animate );
// measure time
lastTimeMsec = lastTimeMsec || nowMsec-1000/60
var deltaMsec = Math.min(200, nowMsec - lastTimeMsec)
lastTimeMsec = nowMsec
// call each update function
onRenderFcts.forEach(function(onRenderFct){
onRenderFct(deltaMsec/1000, nowMsec/1000)
})
})
})()
```
--------------------------------
### Initialize Multi-Marker Controls
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/multi-markers/examples/threex-screenasportal/examples/screenAsPortal-original.html
Initializes `ArMarkerHelper` for each sub-marker and adds their 3D objects to the scene. This setup is crucial for managing individual markers within a multi-marker configuration.
```javascript
var markerHelpers = []
multiMarkerControls.subMarkersControls.forEach(function(subMarkerControls){
var markerHelper = new THREEx.ArMarkerHelper(subMarkerControls)
subMarkerControls.object3d.add( markerHelper.object3d )
markerHelpers.push(markerHelper)
})
```
--------------------------------
### Reduce Shaking with Smoothing Factor
Source: https://github.com/ar-js-org/ar.js/blob/master/aframe/examples/location-based/README.md
A modified 'basic-js' example that incorporates a smoothing factor to mitigate camera shaking effects. Adjust the smoothing factor to fine-tune the stability.
```javascript
AFRAME.registerComponent('avoid-shaking', {
schema: {
smoothingFactor: {
type: 'number',
default: 0.1
}
},
init: function () {
const scene = this.el;
// ... (logic to create boxes)
const positions = [
{ x: 0, y: 1.5, z: -5 },
{ x: 0, y: 1.5, z: -15 },
{ x: 10, y: 1.5, z: -10 },
{ x: -10, y: 1.5, z: -10 }
];
const colors = ['red', 'blue', 'green', 'orange'];
let previousPositions = positions.map(() => ({ x: 0, y: 0, z: 0 }));
positions.forEach((pos, index) => {
const box = document.createElement('a-box');
// Apply smoothing
const smoothedPos = {
x: pos.x * this.data.smoothingFactor + previousPositions[index].x * (1 - this.data.smoothingFactor),
y: pos.y * this.data.smoothingFactor + previousPositions[index].y * (1 - this.data.smoothingFactor),
z: pos.z * this.data.smoothingFactor + previousPositions[index].z * (1 - this.data.smoothingFactor)
};
box.setAttribute('position', `${smoothedPos.x} ${smoothedPos.y} ${smoothedPos.z}`);
box.setAttribute('rotation', '0 45 0');
box.setAttribute('color', colors[index]);
scene.appendChild(box);
previousPositions[index] = smoothedPos;
});
}
});
```
--------------------------------
### ES6 Import Map for AR.js Modules
Source: https://github.com/ar-js-org/ar.js/blob/master/README.md
This example demonstrates how to configure an import map to use AR.js modules like ar-threex.mjs with ES6 import syntax. Ensure the 'three' import points to a valid Three.js module path.
```html
// Example importing ar-threex.mjs
```
--------------------------------
### Starting and Stopping AR.js GPS Tracking
Source: https://context7.com/ar-js-org/ar.js/llms.txt
Starts and stops the GPS tracking service for the LocationBased AR module. Includes a commented-out example for faking GPS positions for testing.
```javascript
// Start GPS tracking
locationBased.startGps();
// For testing: fake GPS position
// locationBased.fakeGps(-0.723, 51.049, 10, 5); // lon, lat, elevation, accuracy
// Cleanup
locationBased.stopGps();
```
--------------------------------
### Always Face User Text Example
Source: https://github.com/ar-js-org/ar.js/blob/master/aframe/examples/location-based/README.md
Displays text north of the user's location, utilizing an A-Frame 'look-at' component to ensure the text continuously faces the camera. Requires the 'look-at' component to be installed.
```html
```
--------------------------------
### Initialize ARToolkitSource
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/nft.html
Sets up the ARToolkit source, typically a webcam, and handles resizing to fit the screen. Includes event listeners for initialization and window resize.
```javascript
// handle arToolkitSource
const arToolkitSource = new ArToolkitSource({
sourceType : 'webcam',
sourceWidth: 480,
sourceHeight: 640,
})
arToolkitSource.init(function onReady(){
// use a resize to fullscreen mobile devices
setTimeout(function() {
onResize()
}, 1000);
})
// handle resize
window.addEventListener('resize', function(){
onResize()
})
// listener for end loading of NFT marker
window.addEventListener('arjs-nft-loaded', function(ev){
console.log(ev);
})
function onResize(){
arToolkitSource.onResizeElement()
arToolkitSource.copyElementSizeTo(renderer.domElement)
if( arToolkitContext.arController !== null ){
arToolkitSource.copyElementSizeTo(arToolkitContext.arController.canvas)
}
}
```
--------------------------------
### Initialize AR Toolkit and Renderer
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/measure-it.html
Sets up the WebGL renderer and the ARToolkit context. The renderer is configured for transparency and appended to the body. The ARToolkit context requires camera parameters and a detection mode.
```javascript
import * as THREE from 'three'
import { ArToolkitSource, ArToolkitContext, ArMarkerControls } from 'threex'
ArToolkitContext.baseURL = '../'
// init renderer
var renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setClearColor(new THREE.Color('lightgrey'), 0)
renderer.setSize(640, 480);
renderer.domElement.style.position = 'absolute'
renderer.domElement.style.top = '0px'
renderer.domElement.style.left = '0px'
document.body.appendChild(renderer.domElement);
// array of functions for the rendering loop
var onRenderFcts = [];
var arToolkitContext, markerControls;
// init scene and camera
var scene = new THREE.Scene();
// Create a camera
var camera = new THREE.Camera();
scene.add(camera);
```
--------------------------------
### Initialize AR.js Context and Source
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/multi-markers/examples/tmp/player-old.html
Sets up the AR.js context with camera parameters and detection mode, and initializes the AR.js source from the webcam. Handles resizing of the renderer and AR controller canvas.
```javascript
var arToolkitSource = new THREEx.ArToolkitSource({
// to read from the webcam
sourceType : 'webcam',
//
// to read from an image
// sourceType : 'image',
// sourceUrl : THREEx.ArToolkitContext.baseURL + '../data/images/multimarker.jpg'
// to read from a video
// sourceType : 'video',
// sourceUrl : THREEx.ArToolkitContext.baseURL + '../data/videos/headtracking.mp4',
})
arToolkitSource.init(function onReady(){
// handle resize of renderer
arToolkitSource.onResize([renderer.domElement, arToolkitContext.arController.canvas])
})
// handle resize
window.addEventListener('resize', function(){
// handle arToolkitSource resize
arToolkitSource.onResize([renderer.domElement, arToolkitContext.arController.canvas])
})
// create atToolkitContext
var arToolkitContext = new THREEx.ArToolkitContext({
cameraParametersUrl: THREEx.ArToolkitContext.baseURL + '../data/data/camera_para.dat',
detectionMode: 'mono',
maxDetectionRate: 30,
canvasWidth: 80*4,
canvasHeight: 60*4,
})
// initialize it
arToolkitContext.init(function onCompleted(){
// copy projection matrix to camera
camera.projectionMatrix.copy( arToolkitContext.getProjectionMatrix() );
})
// update artoolkit on every frame
onRenderFcts.push(function(){
if( arToolkitSource.ready === false ) return
arToolkitContext.update( arToolkitSource.domElement )
})
```
--------------------------------
### Initialize Learner Parameters
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/multi-markers/examples/tmp/player-old.html
Sets up the parameters for the learner application, including the back URL and marker controls configuration. This object is then used to link the learner to the AR experience.
```javascript
var learnerParameters = {
backURL : 'player.html',
markersControlsParameters: markersControlsParameters,
}
```
--------------------------------
### Initialize Basic Camera
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/boilerplate-threejs.html
Creates a perspective camera with specified field of view, aspect ratio, and near/far clipping planes. Includes a resize listener to update camera properties.
```javascript
var camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.01, 100 );
camera.position.z = 3;
window.addEventListener( 'resize', function() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}, false );
```
--------------------------------
### Initialize AR.js Context and Source
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/default-thinner-border.html
Initializes the AR.js context and source, setting up the webcam or image as the input for AR tracking. Includes event listeners for resizing.
```javascript
import * as THREE from 'three'
import { ArSmoothedControls, ArToolkitSource, ArToolkitContext, ArToolkitProfile, ArMarkerControls } from 'threex'
ArToolkitContext.baseURL = '../'
var renderer = new THREE.WebGLRenderer({
// antialias : true,
alpha: true
});
renderer.setClearColor(new THREE.Color('lightgrey'), 0)
// renderer.setPixelRatio( 2 );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.domElement.style.position = 'absolute'
renderer.domElement.style.top = '0px'
renderer.domElement.style.left = '0px'
document.body.appendChild( renderer.domElement );
var onRenderFcts = [];
var scene = new THREE.Scene();
var camera = new THREE.Camera();
scene.add(camera);
var artoolkitProfile = new ArToolkitProfile()
// artoolkitProfile.sourceWebcam()
artoolkitProfile.sourceImage(ArToolkitContext.baseURL + '../test/data/images/marker-artoolkit-pattern-pattratio-09.png')
var arToolkitSource = new ArToolkitSource(artoolkitProfile.sourceParameters)
arToolkitSource.init(function onReady() {
onResize()
})
window.addEventListener('resize', function() {
onResize()
})
function onResize() {
arToolkitSource.onResizeElement()
arToolkitSource.copyElementSizeTo(renderer.domElement)
if (arToolkitContext.arController !== null) {
arToolkitSource.copyElementSizeTo(arToolkitContext.arController.canvas)
}
}
var arToolkitContext = new ArToolkitContext(artoolkitProfile.contextParameters)
arToolkitContext.init(function onCompleted() {
camera.projectionMatrix.copy(arToolkitContext.getProjectionMatrix());
})
onRenderFcts.push(function() {
if (arToolkitSource.ready === false)
return
arToolkitContext.update(arToolkitSource.domElement)
})
```
--------------------------------
### Initialize AR.js Context and Renderer
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/multi-markers/examples/tmp/default.html
Sets up the WebGL renderer, scene, and camera. Initializes the ARToolkitContext and ARToolkitSource for webcam input. Handles window resizing to maintain aspect ratio.
```javascript
THREEx.ArToolkitContext.baseURL = '../../../'
// init renderer
var renderer = new THREE.WebGLRenderer({
// antialias : true,
alpha: true
});
renderer.setClearColor(new THREE.Color('lightgrey'), 0)
// renderer.setPixelRatio( 2 );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.domElement.style.position = 'absolute'
renderer.domElement.style.top = '0px'
renderer.domElement.style.left = '0px'
document.body.appendChild( renderer.domElement );
// array of functions for the rendering loop
var onRenderFcts=[];
// init scene and camera
var scene = new THREE.Scene();
// Create a camera
var camera = new THREE.Camera();
scene.add(camera);
// arToolkitProfile.sourceWebcam()
var arToolkitProfile = new THREEx.ArToolkitProfile()
artoolkitProfile.sourceWebcam()
var arToolkitSource = new THREEx.ArToolkitSource(artoolkitProfile.sourceParameters)
arToolkitSource.init(function onReady(){
// handle resize of renderer
arToolkitSource.onResize([renderer.domElement, arToolkitContext.arController.canvas])
})
// handle resize
window.addEventListener('resize', function(){
// handle arToolkitSource resize
arToolkitSource.onResize([renderer.domElement, arToolkitContext.arController.canvas])
})
// create atToolkitContext
var arToolkitContext = new THREEx.ArToolkitContext(artoolkitProfile.contextParameters)
// initialize it
arToolkitContext.init(function onCompleted(){
// copy projection matrix to camera
camera.projectionMatrix.copy( arToolkitContext.getProjectionMatrix() );
})
// update artoolkit on every frame
onRenderFcts.push(function(){
if( arToolkitSource.ready === false ) return
arToolkitContext.update( arToolkitSource.domElement )
})
```
--------------------------------
### Initialize AR.js and Three.js
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/mobile-performance.html
Sets up the Three.js renderer, scene, and camera, and initializes AR.js components for webcam-based augmented reality.
```javascript
import * as THREE from 'three'
import { ArSmoothedControls, ArToolkitSource, ArToolkitContext, ArMarkerControls } from 'threex'
ArToolkitContext.baseURL = '../'
// init renderer
var renderer = new THREE.WebGLRenderer({
// antialias : true,
alpha: true
});
renderer.setClearColor(new THREE.Color('lightgrey'), 0)
// renderer.setPixelRatio( 1/2 );
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.domElement.style.position = 'absolute'
renderer.domElement.style.top = '0px'
renderer.domElement.style.left = '0px'
document.body.appendChild(renderer.domElement);
// array of functions for the rendering loop
var onRenderFcts = []
var arToolkitContext, artoolkitMarker, markerRoot;
// init scene and camera
var scene = new THREE.Scene();
// Create a camera
var camera = new THREE.Camera();
scene.add(camera);
markerRoot = new THREE.Group
scene.add(markerRoot)
```
--------------------------------
### Initialize AR.js and Three.js Scene
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/minimal_ES6.html
Sets up the renderer, scene, and camera. It also initializes the ARToolkit source from the webcam and adds the renderer's DOM element to the document body.
```javascript
import * as THREE from 'three'
import { ArToolkitSource, ArToolkitContext, ArMarkerControls } from 'threex'
ArToolkitContext.baseURL = '../'
////////////////////////////////////////////////////////////////////////////////
// Init
////////////////////////////////////////////////////////////////////////////////
const cameraParam = "../../data/data/camera_para.dat"
var arToolkitSource, arToolkitContext, arMarkerControls;
// init renderer
var renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setClearColor(new THREE.Color('lightgrey'), 0)
renderer.setSize( 640, 480 );
renderer.domElement.style.position = 'absolute'
renderer.domElement.style.top = '0px'
renderer.domElement.style.left = '0px'
document.body.appendChild( renderer.domElement );
// array of functions for the rendering loop
var onRenderFcts=[];
// init scene and camera
var scene = new THREE.Scene();
////////////////////////////////////////////////////////////////////////////////
// Initialize a basic camera
////////////////////////////////////////////////////////////////////////////////
// Create a camera
var camera = new THREE.Camera();
scene.add(camera);
//////////////////////////////////////////////////////////////////////////////
// handle arToolkitSource
//////////////////////////////////////////////////////////////////////////////
arToolkitSource = new ArToolkitSource({
// to read from the webcam
sourceType : 'webcam',
sourceWidth: window.innerWidth > window.innerHeight ? 640 : 480,
sourceHeight: window.innerWidth > window.innerHeight ? 480 : 640,
})
arToolkitSource.init(() => {
arToolkitSource.domElement.addEventListener('canplay', () => {
console.log( 'canplay', 'actual source dimensions', arToolkitSource.domElement.videoWidth, arToolkitSource.domElement.videoHeight );
initARContext();
});
window.arToolkitSource = arToolkitSource;
});
```
--------------------------------
### Initialize Renderer and Scene
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/boilerplate-threejs.html
Sets up the WebGL renderer, appends it to the body, and initializes the three.js scene. Handles window resizing to update camera and renderer.
```javascript
var renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.domElement.style.position = 'absolute'
renderer.domElement.style.top = '0px'
renderer.domElement.style.left = '0px'
document.body.appendChild( renderer.domElement );
var onRenderFcts=[];
var scene = new THREE.Scene();
```
--------------------------------
### Initialize ARToolKit Camera
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/multi-markers/examples/player.html
Creates a Three.js camera, specifically for the ARToolKit tracking backend. Ensure urlOptions.trackingBackend is set correctly.
```javascript
if( urlOptions.trackingBackend === 'artoolkit' ){
var camera = new THREE.Camera();
}else
console.assert(false)
scene.add(camera);
```
--------------------------------
### Customize TweenControls Animation
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/multi-markers/examples/threex-tweencontrols/examples/basic.html
Allows customization of the delay before a tween animation starts and the easing function used for the animation.
```javascript
// customize the delay to tween
tweenControls.tweenDelay = 1
// customize the function to tween
tweenControls.tweenFunction = THREEx.TweenControls.Easing.Quintic.Out
```
--------------------------------
### Initialize WebGL Renderer
Source: https://github.com/ar-js-org/ar.js/blob/master/three.js/examples/marker-training/examples/patternmarker-from-image.html
Sets up the WebGL renderer for the AR scene. Ensure the renderer is appended to the document body to display the AR content.
```javascript
var renderer = new THREE.WebGLRenderer({
// antialias : true,
alpha: true
});
renderer.setClearColor(new THREE.Color('lightgrey'), 0)
// renderer.setPixelRatio( 2 );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.domElement.style.position = 'absolute'
renderer.domElement.style.top = '0px'
renderer.domElement.style.left = '0px'
document.body.appendChild( renderer.domElement );
```