To create a three.js page that loads a 3D model, you'll need to do the following steps:
- Create an HTML file that includes the necessary scripts and libraries.
<!DOCTYPE html>
<html>
<head>
<title>Three.js Model Loader</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdn.jsdelivr.net/npm/three@0.133.2/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.133.2/examples/js/loaders/MTLLoader.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.133.2/examples/js/loaders/OBJLoader.js"></script>
</head>
<body>
<div id="model-container"></div>
<script src="js/main.js"></script>
</body>
</html>
In this example, we're using the latest version of three.js, as well as the MTLLoader and OBJLoader scripts from the examples folder.
- Create a main.js file that loads the model and adds it to the scene.
// Initialize the scene, camera and renderer
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
// Load the materials and geometry of the model
var mtlLoader = new THREE.MTLLoader();
mtlLoader.load( 'model.mtl', function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.load( 'model.obj', function ( object ) {
scene.add( object );
});
});
// Add lights to the scene
var ambientLight = new THREE.AmbientLight( 0xcccccc, 0.4 );
scene.add( ambientLight );
var pointLight = new THREE.PointLight( 0xffffff, 0.8 );
camera.add( pointLight );
scene.add( camera );
// Set the position of the camera
camera.position.z = 5;
// Render the scene
function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
}
animate();
In this example, we're using MTLLoader to load the materials of the model, and OBJLoader to load the geometry. Once both the materials and geometry have been loaded, we add the object to the scene. We're also adding ambient and point lights to the scene and positioning the camera to view the object.
- Place the model files and images in the correct location within your project directory.
Your project directory should look something like this:
project/
index.html
js/
main.js
model/
model.mtl
model.obj
img/
texture.jpg
- Open the index.html file in your browser to view the loaded 3D model.
That's it! You should now have a three.js page that loads your 3D model.