model viewer

model-viewer from Google

Web is evolving. And Google is helping a lot.

If you want to display 3D models with some annotations, and even with animations, you can do it with <model-viewer>. This performant and progressive web component can be used in many ways, and supports the beloved augmented reality tech.🥰

Inserting the 3D Model

Currently, it supports .gltf and .glb 3D model formats. We already have our .glb model, so let’s dive right now to the code.

Create a new file called index.html and start by writing the basic HTML document tags and move your 3D model to the same folder. Then inside our <head> section paste these lines, they make it easier to call the necessary packages:

<script type="module" src="https://unpkg.com/@google/model-viewer/dist/model-viewer.js"></script><script nomodule src="https://unpkg.com/@google/model-viewer/dist/model-viewer-legacy.js"></script>

Then on our <body> section, we can embed our 3D model like this:

<model-viewer camera-controls src="assets/Dotesfera3D.glb"
alt="A simple 3D model">

After this, open your index.html on your browser and you should see your 3D model. You can now rotate and zoom in/out because of the camera-controls attribute.

Sometimes we want to give more information about the model. We can do it with Hotspots. Let’s add one, by simply adding a <button> with some custom attributes that <model-viewer> will interpret as data:

<button slot=”hotspot” data-position=”0.13m 0.018m 0.31m”> <div id=”annotation”>This is the nucleus</div></button>

In the above code we use data-position to tell where the Hotspot will be positioned on the 3D model. The coordinates (x,y,z) are shown in meters because of the scale of our example model. We also used the slot attribute, learn more here.

We can also add a skybox to our viewer by using the skybox-image attribute:

<model-viewer camera-controls src="assets/Dotesfera3D.glb"
alt="A simple 3D model" skybox-image="./photo.jpg">

And so far this is our result:

But that’s not it! If we add the ar attribute to our code like this:

<model-viewer camera-controls src="assets/Dotesfera3D.glb"
alt="A simple 3D model" skybox-image="./photo.jpg"
ar ar-modes="wexr">

And if you open your project on a smartphone you can see a special feature where you can view the 3D model positioned in the real world on a real scale with augmented reality (also compatible with Magic Leap, and Quick Look on iOS). Just click the button:

model viewer
Botão de modo AR

Then it’ll launch AR mode!

So what do you think? Easy right?

Start typing and press Enter to search