Augmented Reality in 10 Lines of HTML

AR.js with a-frame magic

Do you want to do Augmented Reality on the web ? You can now do it in 10 lines of HTML! Seriously! Let me walk you thru the code, it’s crazy simple.

We released AR.js recently. You can experience efficient augmented reality for the web directly on your phone without installing any applications. But let’s go further and see how to produce your own augmented reality experience. The shortest example of AR.js is only 10lines of HTML thanks to the magic of a-frame. You can see it live on codepen:

AR.js example in 10 lines of HTML

Let’s break it down line by line.

Including the Libraries

scripts to include

First, you include a-frame, an effort started by MozillaVR to build VR experiences. A-frame contains three.js. Then you simply include AR.js for a-frame. AR.js will make the 3d displayed in AR run very fast on your phone, even if it’s a 2–3 year old phone!

Defining the Body

Usual html body — not much here

In this step, it’s all business as usual. You define the body, like you would in all HTML pages.

Creating a 3d Scene

Declare your scene, and specify you are using artoolkit

Next, we are going to create our a-frame scene. We also need to add the ARToolkit component. ARToolKit is an open-source library that we use to localize it through the phone camera.

Adding Simple Content

Just a simple box

Once we have created the 3d scene, we can start adding objects to it. In this line, we add a simple box. We then modify its material to make it transparent. We also change its position so it displays on top of the AR marker.

Adding the AR Camera

Define a camera controlled by marker position

In this last step, we are going to add a camera. We include the preset ‘hiro’ (as in Hiro marker). Finally, we make it move as if it were your phone. Easy right?

Congratulations! You are done. You now have augmented reality, in only 10 lines of HTML, running fast on your phone and free of charge.

Check out this video version I made of the tutorial:


Thanks for reading, and if you like this post, don’t forget to share 😉

Also, please feel free to contact me anytime @AndraConnect