Three.js is a powerful JavaScript library for displaying 3D graphics in a web browser. To effectively use 3D models in your Three.js projects, you'll need to understand how to host these assets and then load them into your scene.
3D assets, such as models, textures, and animations, are typically static files that need to be served by a web server. Here are common methods for hosting them:
For development, you can use a simple local HTTP server (e.g., Node.js http-server, Python's http.server, or npx serve). This allows your browser to access the files from your local machine.
npx serve .
CDNs are highly recommended for production environments. They distribute your assets across multiple servers globally, reducing latency and improving loading times for users worldwide.
Services like Amazon S3, Google Cloud Storage, or Azure Blob Storage are excellent for hosting static assets. They offer high availability, scalability, and can be integrated with CDNs.
If you have a dedicated web server (e.g., Apache, Nginx), you can place your 3D asset files in a publicly accessible directory.
Three.js uses various "loaders" to import different 3D file formats. The most recommended and widely adopted format for web-based 3D is glTF (GL Transmission Format), often referred to as the "JPEG of 3D" due to its efficiency and suitability for web delivery.
GLTFLoader:import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
// Instantiate a loader
const loader = new GLTFLoader();
// Load a glTF resource
loader.load(
// resource URL
'path/to/your_model.gltf', // or .glb
// called when the resource is loaded
function ( gltf ) {
scene.add( gltf.scene );
},
// called while loading is progressing
function ( xhr ) {
console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
},
// called when loading has errors
function ( error ) {
console.error( 'An error happened', error );
}
);
While glTF is preferred, Three.js also supports other formats with dedicated loaders:
OBJLoader for .obj files.FBXLoader for .fbx files.TextureLoader for image textures (e.g., .jpg, .png).