ThreeJS编写载入gltf模型源码【3D货车模型动画】
使用Three.JS开发网页载入gltf模型显示,包括动画,载入得模型包括3D货车gltf模型,3D小黄鸭模型,3D人行走动画模型,3D怪兽模型,3D轮廓边模型等,完全不需要安装任何插件,输入打开网址就可以查看网上3D产品在线展示。
展示源码功能包括:
1.场景默认显示带贴图质感和动画得3D货车在行驶;
2.可以通过鼠标控制视点切换,鼠标按下旋转视点,滑轮缩放,整个场景的背景是全景黑色背景;
3.右上角具有一个控制菜单,可以选择显示gltf格式模型,可以选择不同材质纹理贴图格式的模型,支持切换测试载入glb格式【gltf的二进制格式模型】;
注:本地预览建议部署WEB服务器,配置localhost/127.0.0.1等网络访问地址运行,建议用火狐浏览器,谷歌浏览器等。
核心源码如下
//使用载入gltf模型封装类
loader = new GLTFLoader();
var dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath( ‘js/libs/draco/gltf/’ );
loader.setDRACOLoader( dracoLoader );
loader.setDDSLoader( new DDSLoader() );
var url = sceneInfo.url.replace( /%s/g, state.extension );
if ( state.extension === ‘glTF-Binary’ ) {
url = url.replace( ‘.gltf’, ‘.glb’ );
}
var loadStartTime = performance.now();
loader.load( url, function ( data ) {
gltf = data;
var object = gltf.scene;
console.info( ‘Load time: ‘ + ( performance.now() – loadStartTime ).toFixed( 2 ) + ‘ ms.’ );
if ( sceneInfo.cameraPos ) {
camera.position.copy( sceneInfo.cameraPos );
}
if ( sceneInfo.center ) {
orbitControls.target.copy( sceneInfo.center );
}
if ( sceneInfo.objectPosition ) {
object.position.copy( sceneInfo.objectPosition );
if ( spot1 ) {
spot1.target.position.copy( sceneInfo.objectPosition );
}
}
if ( sceneInfo.objectRotation ) {
object.rotation.copy( sceneInfo.objectRotation );
}
if ( sceneInfo.objectScale ) {
object.scale.copy( sceneInfo.objectScale );
}
if ( sceneInfo.addEnvMap ) {
object.traverse( function ( node ) {
if ( node.material && ( node.material.isMeshStandardMaterial ||
( node.material.isShaderMaterial && node.material.envMap !== undefined ) ) ) {
node.material.envMap = envMap;
node.material.envMapIntensity = 1.5; // boombox seems too dark otherwise
}
} );
scene.background = background;
}
object.traverse( function ( node ) {
if ( node.isMesh || node.isLight ) node.castShadow = true;
} );
var animations = gltf.animations;
if ( animations && animations.length ) {
mixer = new THREE.AnimationMixer( object );
for ( var i = 0; i < animations.length; i ++ ) {
var animation = animations[ i ];
// There’s .3333 seconds junk at the tail of the Monster animation that
// keeps it from looping cleanly. Clip it at 3 seconds
if ( sceneInfo.animationTime ) {
animation.duration = sceneInfo.animationTime;
}
var action = mixer.clipAction( animation );
if ( state.playAnimation ) action.play();
}
}
scene.add( object );
onWindowResize();
}, undefined, function ( error ) {
console.error( error );
} );
WEBGL学习网 » ThreeJS编写载入gltf模型源码【3D货车模型动画】