Subscribe to our free newsletter

To make sure you won't miss any valuable content we share with our community.

How to Load an OBJ 3D Model with its Texture in Three JS?

Most of the 3D models that we want to use in games, such as characters, furniture, closed areas, rooms, cars, etc, are designed in the OBJ format and naturally, they have a texture too. The texture is usually exported in the MTL file format. Most of the prepared free models that you will find different on websites that offer 3D models for free like Thingiverse, will give a zip file containing OBJ and MTL file formats. In this tutorial, we will focus on importing OBJ and MTL files in Three JS. This tutorial is an important part of designing your game, animation, or any other kind of web application because there are already many free 3D designs out there on the internet. You only need to import and use them in your scene. So now, let’s get started with the project. Don’t forget to find a 3D model of your choice from where ever you like. Notice that the file needs to have .obj and .mtl file formats. Some of these models have a .png or .jpg photo with them.

A simple example from scratch:

We will get started with the main elements of a Three js scene, including the camera, the renderer, the scene, and the object. Before doing that, we use the Vite plugin to easily create all the folders and files you need to run the Three.js code. First off, create a folder in the directory of your projects by using the following commands: mkdir OBJLoader
cd OBJLoader
Then, inside of your project folder, create the necessary files and folders by simply running the Vite plugin command: npm create [email protected] Then enter the name of the project. You can write the name of your project as the name. And also the package (the name is arbitrary, and you can choose anything you want). Then select vanilla as the framework and variant. After that, enter the following commands in the terminal. Notice that here OBJLoader is the project folder’s name, and thus, we have changed the directory to OBJLoader. The name depends on the name you enter in the Vite plugin : cd OBJLoader
npm install
Afterward, you can enter the JavaScript code you want to write in the main.js file. So, we will enter the base or template code for running every project with an animating object, such as a sphere. Also, do not forget to install the Three.js package library every time you create a project: npm install three

Importing the OBJ 3D model:

Now, enter the following script in the main.js file:

import * as THREE from 'three';
import { Mesh } from 'three';
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader';
import { MTLLoader } from 'three/examples/jsm/loaders/MTLLoader';
import {OrbitControls} from "/node_modules/three/examples/jsm/controls/OrbitControls.js";
import Stats from "/node_modules/three/examples/jsm/libs/stats.module.js";

const scene = new THREE.Scene();
const pointLight = new THREE.PointLight(0xffffff,5);
pointLight.position.set(0,8000,0);
pointLight.intensity = 5;
scene.add(pointLight);

const pointLight2 = new THREE.PointLight(0xffffff,5);
pointLight2.position.set(2000,3000,4000);
pointLight2.intensity = 5;
scene.add(pointLight2);

const width = 20;
const height = 20;
const intensity = 5;
const rectLight = new THREE.RectAreaLight( 0xffffff, intensity,width, height );
rectLight.position.set( 5000, 5000, 5000 );
scene.add( rectLight );

const camera = new THREE.PerspectiveCamera(75, innerWidth/innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({
     antialias : true
});

renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
const controls = new OrbitControls(camera,renderer.domElement);

//Loading the MTL and OBJ files
var mtlLoader = new MTLLoader();
mtlLoader.load('/Models/plane.mtl',function(materials){
     materials.preload();
     var objLoader = new OBJLoader();
     objLoader.setMaterials(materials);
     objLoader.load('/Models/plane.obj',function(object){
          scene.add(object);
     });
});

camera.position.z = 15;
window.addEventListener('resize', onWindowResize, false);

function onWindowResize() {
     camera.aspect = window.innerWidth / window.innerHeight;
     camera.updateProjectionMatrix();
     renderer.setSize(window.innerWidth, window.innerHeight);
     render();
};

const stats = Stats()
document.body.appendChild(stats.dom)
function animate() {
     requestAnimationFrame(animate);
     render();
     //stats.update();
};

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

animate();


Now if we save the code, and enter the following command in the terminal: npm run dev The above script will give the following result:

As you can see, we are observing the smallest details of an airplane with all the textures of the different parts.

Explaining the code:

As always, we added the necessary elements of every scene, such as the scene itself, the camera, the renderer, the orbit controls, and the animation function. Notice that we also imported all the necessary packages for our purpose. The main part of this code is related to loading the OBJ and MTL files where we first imported the MTL and inside of its function added the OBJ file as well. In other words, MTL is the material of the OBJ object. It is like creating an object and adding its material to it. Notice that most of the objects that you find on the internet, are very large or they could be in size. So you should set the lights and the camera according to the dimensions of the given object. Otherwise, you will see nothing or you have to zoom in or zoom out so much in order to see the object clearly. Also, the lighting might not display the object properly. So, you have to set the position and intensity of it, too. We have placed the models in the Models folder and have imported them according to their names. Make sure you set the names according to your files and you should have the files ready for display!

Conclusion

In this tutorial, we have managed to import an object and its texture using the OBJ loader and MTL loader in Three JS. Using such a tool, we can import as many 3D models as we want to create the animation, game, or web application of our choice using Three JS. The .mtl file format works like the material of the object which is imported in the format of .obj. Hope this tutorial has helped you import the 3D models that you like in your Three.js scenes.

Download this Article in PDF format

3d websites

Arashtad Custom Services

In Arashtad, we have gathered a professional team of developers who are working in fields such as 3D websites, 3D games, metaverses, and other types of WebGL and 3D applications as well as blockchain developemnet.

Arashtad Serivces
Drop us a message and tell us about your ideas.
Fill in the Form
Blockchain Development

Three.js Object3D: A Tool to Manipulate Objects

The main purpose of this tutorial is to make you familiar with the steps we take to create a very simple project in Three.js. Then, we run it and then manipulate the scene including the object, the camera, and the light or lights depending on the use case. Of course, this tutorial is for beginners who want to take their very first steps into the world of Three.js Object3D and start some simple manipulations on the scene.

Manipulating Objects Using Three.js Object3D

In this article, we are going to cover the basics of creating an object, camera, and lights. Then, we’ll start manipulating objects and see the different effects we can create on the objects using the functions provided by Three.js.

A scene is where you place the objects, the camera, and lights, a space that you render the objects in, and in general where you determine what and where the elements should be placed. Each scene has three main elements:
  1. The camera
  2. The object or objects
  3. The light source or the light sources
Most of the time when you want to create a new project in Three.js, you first set up all of these 3 main elements. And then, you go after the details of the light, camera and the object itself. Consequently, before we start manipulating our first scene, we should set up the dependencies and create a boilerplate to develop and manipulate the primary object.

A Simple Project to Check Three.js Object3D

First off, make sure you have npm installed. You can start your first project by git cloning one of the simple Three.js projects to find a boilerplate for further development. Most of these projects can be found on Github, animate simple objects like a cube, sphere, torus, and so on. The animation is usually rotation.

Running these projects and developing them step by step by changing some of the features about rendering, lighting, camera perspective, the color of the objects, textures, animations, and so on will help you find the necessary tools to design more complex objects. We start our first project by git cloning one of the Github repositories. To do so, enter the following command in the terminal: mkdir Starting_Three
cd Starting_Three
git clone https://github.com/designcourse/threejs-webpack-starter
Then, enter the following commands one by one to install the dependencies: npm install
npm install webpack-dev-server -g
Now, change the directory to threejs-webpack-starter: cd threejs-webpack-starter Then, enter the followings one by one to get a pre-designed 3D animated torus: npm i
npm run dev
npm run build
And you will be able to see the animated (rotating) torus like this in your browser:

Now, let’s head over to our the JavaScript code behind the scenes and see the elements of this 3D design and rendering. In src folder, script.js file, you will some scripts that we are going to modify later.

The Shape of the Object

The shape of the object can be any geometrical shape available on the Three.js official documentation website at https://threejs.org/docs. The most famous ones are box, sphere, torus and so on. We want to modify the raw script using the below code for defining the geometry. Notice that you should replace it with the const geometry in the raw code.

const geometry = new THREE.BoxGeometry(1, 1, 1);


Second of all, we can change the material from basic to standard by writing:

const material = new THREE.MeshStandardMaterial();


Instead of:

const material = new THREE.MeshBasicMaterial();

And then we can apply the metalness , roughness and color effects:

material.metalness = 0.7;
material.roughness = 0.6;
material.color = new THREE.Color(0xB1E1FF);

The next thing that we should do is to modify the renderer a little bit from:

const renderer = new THREE.WebGLRenderer({
 canvas: canvas
})

To:

const renderer = new THREE.WebGLRenderer({
 canvas: canvas,
 alpha: true
})

The light in Three.js Object3D Scripts

There are many different kinds of lights in Three.js and we have covered a full tutorial on that in an article. Here we use Rect light which works the same way as a light coming from a window. We set the color as white and determine the position of the light in addition to the place the light is oriented towards:

const width = 20;
const height = 20;
const intensity = 5;
const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
rectLight.position.set(5, 5, 5);
rectLight.lookAt(0.5, 0.5, 0.5);
scene.add(rectLight);

The Camera in Three.js Object3D Scripts

The camera is another element of the scene that you can set the position of it in the Three.js scripts. The position position of the camera is like the eye of the viewer. So you can either change the position of the object relative to camera or vice versa. Both ways you will get the same out put.

const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height, 0.1, 100);
camera.position.x = 0;
camera.position.y = 0;
camera.position.z = 2;
scene.add(camera);

By saving the code, you will get:

three.js

Final Thought

In this article, we have introduced the key elements of every scene including the camera, the object, and the light. In addition to that, we have provided the guides for creating the very first project you can get started in Three.js. Then we started manipulating the raw code which at first showed the tube with mesh basic and a simple point light and then we changed the geometry to cube, changed the color, the light and finally explained the codes related to each one of the elements in the scene.

Download this Article in PDF format

metaverse

Curious about What We’re Up To?

In Arashtad we provide custom services in various design and development fields. 3D websites, 3D games, metaverses, and other types of WebGL and 3D applications are just some of our expertise.

Arashtad Serivces
Drop us a message and tell us about your ideas.
Request a Quote
3D Development