Load a 3D Model Using the Three.js OBJ Loader

It’s quite simple to create a 3D model viewer by using three.js. In this tutorial I’m going to walk through exactly how to do it and the different options available to us.

How to get started

  1. Clone down the start branch from my three.js boilerplate repository here. This branch includes all of the necessary loaders and 3D files to get started. You can of course use your own file or find one you like for free on Clara. My example is using R2-D2 from Star Wars.

    1. Here are links to the dependencies if you aren’t familiar with github.
      1. OBJLoader
      2. MTLLoader
      3. OrbitControls
  2. Checkout the branch using git
  3. Install the app dependencies
  4. Start the server

Setup

This is the boilerplate I use to start all three.js projects. Add the code below to this in order to finish the project!

Camera

This will differentiate based on the size of your model initially, but I’m going to move the camera back a bit to get a better view.

Controls

I’ve implemented OrbitControls so we can orbit around the model, we even get zoom controls out of the box! Damping is a way of smoothing the zoom process.

We also need to add the update method for out controls to the existing animate function in our scripts.

Lighting

Anytime a 3d object is introduced in three.js, it’s important to have some sophisticated lighting to better display it. Check out my setup below:

Loading the Model

Now it’s time to leverage the MTLLoader and OBJLoader. First we load the material file, this references the jpg files to draw on the model. In that callback function we then load the actual 3D model itself and apply the materials to it. The callback inside that loader is where we add it to the scene. I’ve also dropped the y value on it to vertically center it in our scene better.

That’s it, you now have a functioning 3D model viewer in just a few minutes of writing code. Note that if you are not using my boilerplate server you’ll need to update the¬†setTexturePath and¬†setPath values on your MTLLoader and OBJLoader instances. The server makes life a lot easier and eliminates cross-origin issues – something you’ll come across a lot when first starting out with three.js.

You can view the final code for this up on Github, along with my other examples.

Leave a Reply