Nomisoft
Menu

Importing 3d models into Three.js

09th January 2017

In this tutorial we're going to load a 3d model and render it to our webpage allowing the user to rotate the model. We're going to use the Three.js library to do so. For the purpose of this tutorial i'm using a 3d model of a Lamborghini available to download at http://tf3dm.com/3d-model/lamborghini-aventador-42591.html

Three.js Lamborghini

View the demo

Firstly we're going to create a new empty page with the following code which loads the Three.js library, the Orbit Controls plugin and our own app.js which will create later.


# index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Three.js 3D Model Test</title>
    </head>
    <body>
        <div id="scene"></div>
        <script src="three.min.js"></script>
        <script src="OrbitControls.js"></script>
        <script src="app.js"></script>
    </body>
</html>

Before we can use our model we need to convert the .OBJ file we've downloaded into a JSON file that Three.js can understand. There's a useful Python script available that lets us do this


pyhon convert_obj_three.py -i Avent.obj -o lamborghini.json

Now that our JSON file is ready we can import it and render it to the screen using the Three.js JSONLoader.


# app.js
var scene;
var camera;
var renderer;

function init() {
    var div = document.getElementById("scene");
    var width  = div.offsetWidth;
    var height = div.offsetHeight;

    /* Setup our scene */
    scene = new THREE.Scene();

    /* Setup our camera */
    camera = new THREE.PerspectiveCamera(70, width / height, 0.1, 1000);
    camera.position.set(0, 5, 5);
    camera.lookAt(scene.position);

    /* Setup our renderer */
    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(width, height);
    div.appendChild(renderer.domElement);

    /* Setup controls */
    controls = new THREE.OrbitControls(camera, renderer.domElement);

    /* Setup lighting */
    var spotLight = new THREE.SpotLight( 0xffffff, 4 );
    spotLight.position.set( 0.75, 7.5, 1.5 );
    spotLight.shadow.mapSize.width = 2048;
    spotLight.shadow.mapSize.height = 2048;
    scene.add( spotLight );

    /* Import our model */
    var loader = new THREE.JSONLoader();
    loader.load('lamborghini.json', function(geometry, materials) {
        mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
        mesh.scale.x = mesh.scale.y = mesh.scale.z = 1.5;
        mesh.rotation.x = - Math.PI / 6;
        mesh.rotation.y = Math.PI / 4;
        mesh.translation = geometry.center();
        scene.add(mesh);
    });

    render();
}

function render() {
    requestAnimationFrame(render);
    controls.update();
    renderer.render(scene, camera);
}

window.onload = init();

View the demo