トップへ(mam-mam.net/)

Using MTLLoader in Three.js | Applying .mtl Materials to OBJ Models

Japanese

Loading OBJ Files with “OBJLoader.js” and Applying Materials with “MTLLoader.js” (Three.js [r145])

Do you want to apply materials to OBJ models in Three.js?
This article explains in detail how to load materials using MTLLoader and how to combine it with OBJLoader in your implementation.

By using MTLLoader, you can assign materials to models loaded from OBJ files.
<script src="./three_r145/loaders/MTLLoader.js"></script>
// Create an instance of MTLLoader
var mtlLoader = new THREE.MTLLoader();
mtlLoader.load('****.mtl', function(materials){
// Process executed when the MTL file is loaded
});

Rotate with left mouse drag, move the camera with right mouse drag, and zoom with the mouse wheel.
On touch devices: swipe to rotate, drag with two fingers to move the camera, and pinch in/out to zoom.

Source Code

<script src="./three_r145/three.min.js"></script>
<script src="./three_r145/OrbitControls.js"></script>
<script src="./three_r145/loaders/OBJLoader.js"></script>
<script src="./three_r145/loaders/MTLLoader.js"></script>
<script src="./three_r145/utils/BufferGeometryUtils.js"></script>

<script>
・・・
//Create an instance of MTLLoader
var mtlLoader = new THREE.MTLLoader();
//Load the .mtl file
mtlLoader.load( './three_r145/obj/sofa_m.mtl', function( materials ) {
  materials.preload();
  var objLoader = new THREE.OBJLoader();
  objLoader.setMaterials(materials);
  //Load the .obj file
  objLoader.load('./three_r145/obj/sofa_m.obj',function(obj){
    obj.traverse(function(child){
      child.castShadow=true;
      child.receiveShadow=true;
      if(child.isMesh){
        child.material.flatShading=false;
      }
      if(child.geometry!==undefined){
        child.geometry=THREE.BufferGeometryUtils.mergeVertices(child.geometry,0.1);
        child.geometry.computeVertexNormals();
      }
    });
    obj.scale.set(0.1,0.1,0.1);
    obj.position.set(0,0,0);
    obj.castShadow=true;
    obj.recieveShadow=true;
    scene.add(obj);
  });
});
</script>

Shade3D was used to create the modeling, OBJ file, and MTL file.

three.jsで使用するOBJファイルとMTLファイルをShade3Dで作成

Back to the list of 3D JavaScript content