Three.js加载obj+mtl(OBJLoader2)

官方案例:OBJLoader2加载
需要导入LoaderSupport.js、OBJLoader2.js、MTLLoader.js
方法实现:

function addObjNew(objDef){//新版本写法
	var objLoader = new THREE.OBJLoader2();
	var callbackOnLoad = function ( event ) {
		model=event.detail.loaderRootNode;//获取模型
		model.children.forEach(function(child) {	
   			       child.material.color = new THREE.Color( 0x666666 );					 					
   			       child.material.shininess = 4;					 					
   			       child.material.shading =THREE.SmoothShading;									
   			       child.material.alphaTest  = 0.1;								 			
   			       child.material.transparent  = true;		
   		    });
		setModelPosition(model);
		scene.add( model );
		addDragControls(model);
		console.log( "加载完成: "+ objDef.objName );
	};
	var onLoadMtl = function ( materials ) {
		objLoader.setModelName( objDef.objName );
		objLoader.setMaterials( materials );
		objLoader.setLogging( true, true );
		objLoader.load( objDef.objPath+objDef.objName, callbackOnLoad, null, null, null, false );
	};
	objLoader.loadMtl( objDef.mtlPath+objDef.mtlName, null, onLoadMtl );
}

传入的参数包括obj文件路径名、obj文件名、mtl文件路径名、mtl文件名

方法调用:

addObjNew({//添加模型 
		objPath:"obj/t_shirt_1_Colorway_1/",
		objName:"t_shirt_1_Colorway_1.obj",
		mtlPath:"obj/t_shirt_1_Colorway_1/",
		mtlName:"t_shirt_1_Colorway_1.mtl"
	});

该实现方式基于的98版本的threejs,可通过在浏览器的控制台输入THREE.REVISION 查看three.js版本

若three.js的版本太低,如86,实现如下:

function addObj2(objDef){//加载drc文件

	model = new THREE.Object3D();
	model.name = 'model';
	scene.add( model );//obj模型
	var mtlLoader = new THREE.MTLLoader();
	mtlLoader.setPath( objDef.texturePath );//mtl与obj的目录路径
	mtlLoader.load( objDef.fileMtl, function( materials ) {//mtl材质名

	materials.preload();

	var objLoader = new THREE.OBJLoader2();
	objLoader.setSceneGraphBaseNode( model );
	objLoader.setMaterials( materials.materials );
	objLoader.setPath( objDef.path );//mtl与obj的目录路径
	objLoader.setDebug( false, false );

	var onSuccess = function ( object3d ) {

		object3d.children.forEach(function(child) {	
				        child.material.color = new THREE.Color( 0x666666 );					 					
				        child.material.shininess = 4;					 					
				        child.material.shading =THREE.SmoothShading;									
				        child.material.alphaTest  = 0.1;								 			
				        child.material.transparent  = true;		
				   	});
		 console.log( 'Loading complete. Meshes were attached to: ' + object3d.name );
		 setModelPosition(object3d);//设置模型位置
	};

    var onProgress = function ( event ) {
    		if ( event.lengthComputable ) {
    			var percentComplete = event.loaded / event.total * 100;
    			var output = 'Download of "' + objDef.fileObj + '": ' + Math.round( percentComplete ) + '%';
    			console.log(output);
    		}
    };

    var onError = function ( event ) {

    		console.error( 'Error of type "' + event.type + '" occurred when trying to load: ' + event.src );
    
    };

    objLoader.load( objDef.fileObj, onSuccess, onProgress, onError );
    });
				

}

你可能感兴趣的:(threejs)