阅读 1729
threeJS做web端3D模型展示

threeJS做web端3D模型展示

先看看效果

引入threeJS

<script src="./js/three.js" type="text/javascript" charset="utf-8"></script>
//手势控制器
<script src="./js/controls.js" type="text/javascript" charset="utf-8"></script>
//模型加载器,还有其他类型如:OBJ,自行更换模型加载器
<script src="./js/FBXLoader.js" type="text/javascript" charset="utf-8"></script>
复制代码

不建议使用模块得方式导入threeJS,会导致未知得问题

承载模型标签设置宽高

<div 
    class="three" 
    ref="three"
>
</div>

.three {
width: 100vw;
height: 100vh;}
//我这里设置的是全屏
复制代码

threeJS JS部分

如果使用vue的话先简化下赋值
const THREE = window.THREE;
init() {
var that = this;

//场景
var scene = new THREE.Scene();

//相机视角
var camera = new THREE.PerspectiveCamera(
    30, 
    this.$refs.three.clientWidth / this.$refs.three.clientHeight, 
    0.1, 
    2000
);

//渲染器
var renderer = new THREE.WebGLRenderer( { antialias: true, alpha: true } );
that.renderer=renderer;renderer.setPixelRatio(devicePixelRatio);
renderer.setSize(this.$refs.three.clientWidth, this.$refs.three.clientHeight);

//设置背景为透明,这样就可以自己加背景图片了
renderer.setClearAlpha(0);this.$refs.three.appendChild(renderer.domElement);

//材质
let sphereGeometry = new THREE.SphereGeometry(30, 50, 50);
let meshMaterial  = new THREE.MeshPhongMaterial({  
    color:0x0000ff,  
    specular:0x4488ee,  
    shininess:12});
meshMaterial.shininess = 100;
let sphere = new THREE.Mesh(sphereGeometry, meshMaterial);
sphere.castShadow = true;scene.add(sphere);

//光源
var ambientLight = new THREE.AmbientLight(0xffffff,1.5);
scene.add(ambientLight);

// 平行光
var directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(80, 100, 50);
scene.add(directionalLight);

//手势控制器
var controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.autoRotate = true;
controls.enablePan = false;
controls.maxDistance = 2;
controls.minDistance = 0.5;
controls.update();

//加载模型
var loader = new THREE.FBXLoader();
loader.load(
    //模型的链接地址,这里的地址必须使用线上地址或者使用本地服务器
    'obj-url.com',
    object => {      
        // object.traverse(function(child) {      
        //   if (child instanceof THREE.Mesh) {      
        //     child.material.emissive = new THREE.Color(1,1,1);      
        //     child.material.emissiveIntensity=1;      
        //     child.material.emissiveMap=child.material.map;      
        //   }      
        // });      
        scene.add(object);      
        camera.position.z = 1;    
    },
    //加载进度
    xhr => {      
        that.progress = parseInt(( xhr.loaded / xhr.total * 100 ));    
    },    
    error => {      
        console.error(error);    
    }
);

//60帧动画,360°自动旋转模型
(function animate() {  
    requestAnimationFrame(animate);  
    controls.update();  
    renderer.render(scene, camera);
})()}

//页面卸载的时候清掉缓存和模型数据
beforeDestroy() {  
    THREE.Cache.clear();  
    this.renderer.dispose();  
    this.renderer.forceContextLoss();  
    this.renderer.domElement = null;  
    this.renderer = null;
}
复制代码

后面会完善这篇文章。

文章分类
前端
文章标签