First AR.js App
Tutorial #1 – First AR.js App
by Michael Colonna
AR.js is an open-source library built on top of A-Frame, three.js, and ARToolKit. It leverages the power of WebGL and WebVR to enable augmented reality experiences that run directly in the browser, with surprisingly smooth results. It is marker-based, with entities attached to physical patterns/barcode-like objects in the user's environment (rather than attached to a cloud of feature points that demarcate a surface).
In this tutorial, we'll be creating a very simple AR.js application in a few lines of HTML!
What you'll need:
A laptop OR mobile device with a webcam/camera
For iOS users
When accessing your web app, you must use Safari and add https:// to the beginning of your URL so that the web app can gain access to your camera
For Android (<=4.4.2) users
Apparently your web app will work on Chrome, although I haven't had the chance to try this myself
For this tutorial I also highly recommend creating a Glitch account, if you haven't already. Glitch provides an interface that allows users to host and deploy small web apps (like ones that are only a few lines of HTML) so that they're accessible from any device. Of course, if you want to host this web app by other means feel free – but I will be using Glitch for the remainder of this tutorial.
Creating Our First AR Web App
Create a new Glitch hello-webpage project. You should get an editor that looks like this:
In the top left corner, you'll see a two-word name for your web app (mine is "nice-stallion"). Whenever you want to access your web app, you can go to "https://[app-name].glitch.me" and see your most recent code running. Pretty sweet for accessing your app from any device!
First, let's import the libraries we need. We need AR.js and A-Frame, so copy and paste the following <script> tags into your header like so:
Next, let's delete the HTML code within the <body> tags. Add these lines of code to the <body>:
What's going on here?
If you're familiar with A-Frame, you might recognize the <a-scene> tags which denote a new A-Frame scene. Essentially, AR.js allows us to port these A-Frame scenes into AR by adding the "embedded arjs" components to the <a-scene> tag.
The <a-marker> tag denotes an environment marker. In this case, the preset is set to "hiro", which means that the app begins to look for this marker in the environment. When it finds the marker, it places the inner <a-box> entity on top of the marker. Since the center of the marker has a local position of "0 0 0", a position of "0 0.5 0" allows the box to appear on top of the marker.
The <a-entity> tag initializes a camera for the scene.
If you're using your mobile device, pull up the same marker on your laptop, and see the processing happening on your phone!