首頁 >web前端 >js教程 >在three.js中如何實作3D模型展示

在three.js中如何實作3D模型展示

亚连
亚连原創
2018-06-14 15:09:033979瀏覽

本篇文章主要介紹了three.js實作3D模型展示的範例程式碼,現在分享給大家,也給大家做個參考。

由於專案需要展示3d模型,所以對three做了點研究,分享出來希望能幫到大家

#先看看效果:

 

three.js整體來說不是很難只要你靜下心來研究研究很快就會上手的

首先我們在頁面上需要創建一個能夠放置3D模型的畫布也可以說是初始化Three

var WIDTH,HEIGHT;
  var  renderer;
  function initThree() {
    WIDTH = document.documentElement.clientWidth/2; <!--{foreach from=$recommended_goods item=rgoods}--> <!-- {/foreach} -->
    HEIGHT = document.documentElement.clientHeight/2;
    /* 渲染器 */
    renderer = new THREE.WebGLRenderer();
    renderer.setSize(WIDTH , HEIGHT);
    renderer.setClearColor(new THREE.Color(0x66666));
    renderer.gammaInput = true;
    renderer.gammaOutput = true;

    document.body.appendChild(renderer.domElement);
  }

透過上面的程式碼不難看出我們設定了在body裡追加了一塊畫布寬高是client的一半顏色為0x66666 這裡要注意的是  renderer = new THREE.WebGLRenderer(); 因為我們所有的設定都是以renderer為物件設定

下來我們需要調整相機即視覺角度

/* 摄像头 */
  var camera;
  function initCamera() {
    var VIEW_ANGLE = 45,
        ASPECT = WIDTH / HEIGHT,
        NEAR = 0.1,
        FAR = 10000;
    camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
    camera.position.set(20, 0, 0);
    //设置视野的中心坐标
    camera.lookAt(scene.position);
  }

以上程式碼主要是控制視覺角度數值可以在後期根據自己的需求去調整

載入場景:

/* 场景 */
   var scene;
   function initScene() {
     scene = new THREE.Scene();
   }

載入燈光效果

/* 灯光 */
  var light,light2,light3;
  function initLight() {
    //平行光
    light = new THREE.DirectionalLight(0xFFFFFF);
    light.position.set(0, 99, 0).normalize();
    scene.add(light);
    //环境光
    light2 = new THREE.AmbientLight(0x999999);
    scene.add(light2);
    //点光源
    light3 = new THREE.PointLight(0x00FF00);
    light3.position.set(300, 0, 0);
    scene.add(light3);
  }

顯示模型物件:

/* 显示对象 */
  var cube;
  function initObject(){
    // ASCII file
    var loader = new THREE.STLLoader();
    loader.addEventListener( &#39;load&#39;, function ( event ) {
      var loading = document.getElementById("Loading");
      loading.parentNode.removeChild(loading);
      var geometry = event.content;
      //砖红色
      var material = new THREE.MeshPhongMaterial( { ambient: 0xff5533, color: 0xff5533, specular: 0x111111, shininess: 200 } );
      //纯黑色
//      var material = new THREE.MeshBasicMaterial( { envMap: THREE.ImageUtils.loadTexture( &#39;http://localhost:8080/textures/metal.jpg&#39;, new THREE.SphericalReflectionMapping() ), overdraw: true } ) ;
      //粉色 带阴影
//      var material = new THREE.MeshLambertMaterial( { color:0xff5533, side: THREE.DoubleSide } );
      //灰色
//      var material = new THREE.MeshLambertMaterial({color: 000000});  //材质设定 (颜色)
      var mesh = new THREE.Mesh( geometry, material );
      var center = THREE.GeometryUtils.center(geometry);
      var boundbox=geometry.boundingBox;
      var vector3 = boundbox.size(null);
      var vector3 = boundbox.size(null);
      console.log(vector3);
      var scale = vector3.length();
      camera.position.set(scale, 0, 0);
      camera.lookAt(scene.position);
      scene.add(camera);
      //利用一个轴对象以可视化的3轴以简单的方式。X轴是红色的。Y轴是绿色的。Z轴是蓝色的。这有助于理解在空间的所有三个轴的方向。
      var axisHelper = new THREE.AxisHelper(800);
      scene.add(axisHelper);

      //周围边框
      bboxHelper = new THREE.BoxHelper();
      bboxHelper.visible = true;
      var meshMaterial = material;
      mainModel = new THREE.Mesh(geometry, meshMaterial);
      bboxHelper.update(mainModel);
      bboxHelper.geometry.computeBoundingBox();
      scene.add(bboxHelper);

      //地板网格
//      var gridHelper = new THREE.GridHelper(500, 40); // 500 is grid size, 20 is grid step
//      gridHelper.position = new THREE.Vector3(0, 0, 0);
//      gridHelper.rotation = new THREE.Euler(0, 0, 0);
//      scene.add(gridHelper);
//      var gridHelper2 = gridHelper.clone();
//      gridHelper2.rotation = new THREE.Euler(Math.PI / 2, 0, 0);
//      scene.add(gridHelper2);
//      var gridHelper3 = gridHelper.clone();
//      gridHelper3.rotation = new THREE.Euler(Math.PI / 2, 0, Math.PI / 2);
//      scene.add(gridHelper3);
//
//      var grid = new THREE.GridHelper(300, 40, 25, [0, 0, 1], 0x000055, 0.2, true, "#FFFFFF", "left");
//      scene.add(grid);
      var x = (boundbox.max.x - boundbox.min.x).toFixed(2);
      var y = (boundbox.max.y - boundbox.min.y).toFixed(2);
      var z = (boundbox.max.z - boundbox.min.z).toFixed(2);
      console.log(x);
      console.log(y);
      console.log(z);
      console.log(boundbox);
      mesh.position.set(0,0,0);
//      mesh.position.x = scene.position.x;
//      mesh.position.y = scene.position.y ;
//      mesh.position.z = scene.position.z;
      scene.add(mesh);
      renderer.clear();
      renderer.render(scene, camera);
    } );
    loader.load( &#39;3dfile/莫比乌斯环.STL&#39; );
  }

這裡根據檔案類型選擇相對應的js引入即可我載入的是STL模型所以我引入的是STLLoader.js

<script src="js/STLLoader.js"></script>

如果需要顯示網格標尺將網格部分程式碼去掉註解即可

下來是控制方法(雖然我沒有在顯示程式碼裡面寫根據鍵盤按鍵放大縮小但還是提供給大家參考)

//控制
  var effect;
  var controls;
  function initControl(){
    effect = new THREE.AsciiEffect( renderer );
    effect.setSize( WIDTH, HEIGHT );
    controls = new THREE.TrackballControls( camera,renderer.domElement);
  }

最後就是一個初始調用了

function animate() {
    requestAnimationFrame( animate );
    controls.update();
    effect.render( scene, camera );
  }

  function threeStart() {
    initThree();
    initScene();
    initCamera();
    initLight();
    initObject();
    initControl();
    animate();
  }

附上完整代碼




  
  WebGL
  
  <script src="js/STLLoader.js"></script>
  
  
  

<script>
  var WIDTH,HEIGHT;
  var renderer;
  function initThree() {
    WIDTH = document.documentElement.clientWidth/2; <!--{foreach from=$recommended_goods item=rgoods}--> <!-- {/foreach} -->
    HEIGHT = document.documentElement.clientHeight/2;
    /* 渲染器 */
    renderer = new THREE.WebGLRenderer();
    renderer.setSize(WIDTH , HEIGHT);
    renderer.setClearColor(new THREE.Color(0x66666));
    renderer.gammaInput = true;
    renderer.gammaOutput = true;

    document.body.appendChild(renderer.domElement);
  }

  /* 摄像头 */
  var camera;
  function initCamera() {
    var VIEW_ANGLE = 45,
        ASPECT = WIDTH / HEIGHT,
        NEAR = 0.1,
        FAR = 10000;
    camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
    camera.position.set(20, 0, 0);
    //设置视野的中心坐标
    camera.lookAt(scene.position);
  }

  /* 场景 */
  var scene;
  function initScene() {
    scene = new THREE.Scene();
  }

  /* 灯光 */
  var light,light2,light3;
  function initLight() {
    //平行光
    light = new THREE.DirectionalLight(0xFFFFFF);
    light.position.set(0, 99, 0).normalize();
    scene.add(light);
    //环境光
    light2 = new THREE.AmbientLight(0x999999);
    scene.add(light2);
    //点光源
    light3 = new THREE.PointLight(0x00FF00);
    light3.position.set(300, 0, 0);
    scene.add(light3);
  }

  /* 显示对象 */
  var cube;
  function initObject(){
    // ASCII file
    var loader = new THREE.STLLoader();
    loader.addEventListener( &#39;load&#39;, function ( event ) {
      var loading = document.getElementById("Loading");
      loading.parentNode.removeChild(loading);
      var geometry = event.content;
      //砖红色
      var material = new THREE.MeshPhongMaterial( { ambient: 0xff5533, color: 0xff5533, specular: 0x111111, shininess: 200 } );
      //纯黑色
//      var material = new THREE.MeshBasicMaterial( { envMap: THREE.ImageUtils.loadTexture( &#39;http://localhost:8080/textures/metal.jpg&#39;, new THREE.SphericalReflectionMapping() ), overdraw: true } ) ;
      //粉色 带阴影
//      var material = new THREE.MeshLambertMaterial( { color:0xff5533, side: THREE.DoubleSide } );
      //灰色
//      var material = new THREE.MeshLambertMaterial({color: 000000});  //材质设定 (颜色)
      var mesh = new THREE.Mesh( geometry, material );
      var center = THREE.GeometryUtils.center(geometry);
      var boundbox=geometry.boundingBox;
      var vector3 = boundbox.size(null);
      var vector3 = boundbox.size(null);
      console.log(vector3);
      var scale = vector3.length();
      camera.position.set(scale, 0, 0);
      camera.lookAt(scene.position);
      scene.add(camera);

      //利用一个轴对象以可视化的3轴以简单的方式。X轴是红色的。Y轴是绿色的。Z轴是蓝色的。这有助于理解在空间的所有三个轴的方向。
      var axisHelper = new THREE.AxisHelper(800);
      scene.add(axisHelper);

      //周围边框
      bboxHelper = new THREE.BoxHelper();
      bboxHelper.visible = true;
      var meshMaterial = material;
      mainModel = new THREE.Mesh(geometry, meshMaterial);
      bboxHelper.update(mainModel);
      bboxHelper.geometry.computeBoundingBox();
      scene.add(bboxHelper);

      //地板网格
//      var gridHelper = new THREE.GridHelper(500, 40); // 500 is grid size, 20 is grid step
//      gridHelper.position = new THREE.Vector3(0, 0, 0);
//      gridHelper.rotation = new THREE.Euler(0, 0, 0);
//      scene.add(gridHelper);
//      var gridHelper2 = gridHelper.clone();
//      gridHelper2.rotation = new THREE.Euler(Math.PI / 2, 0, 0);
//      scene.add(gridHelper2);
//      var gridHelper3 = gridHelper.clone();
//      gridHelper3.rotation = new THREE.Euler(Math.PI / 2, 0, Math.PI / 2);
//      scene.add(gridHelper3);
//
//      var grid = new THREE.GridHelper(300, 40, 25, [0, 0, 1], 0x000055, 0.2, true, "#FFFFFF", "left");
//      scene.add(grid);
      var x = (boundbox.max.x - boundbox.min.x).toFixed(2);
      var y = (boundbox.max.y - boundbox.min.y).toFixed(2);
      var z = (boundbox.max.z - boundbox.min.z).toFixed(2);
      console.log(x);
      console.log(y);
      console.log(z);
      console.log(boundbox);
      mesh.position.set(0,0,0);
//      mesh.position.x = scene.position.x;
//      mesh.position.y = scene.position.y ;
//      mesh.position.z = scene.position.z;
      scene.add(mesh);


      renderer.clear();
      renderer.render(scene, camera);
    } );
    loader.load( &#39;3dfile/莫比乌斯环.STL&#39; );
  }

  //控制
  var effect;
  var controls;
  function initControl(){
    effect = new THREE.AsciiEffect( renderer );
    effect.setSize( WIDTH, HEIGHT );
    controls = new THREE.TrackballControls( camera,renderer.domElement);
  }

  function animate() {
    requestAnimationFrame( animate );
    controls.update();
    effect.render( scene, camera );
  }

  function threeStart() {
    initThree();
    initScene();
    initCamera();
    initLight();
    initObject();
    initControl();
    animate();
  }
</script>

Loading...

哦我的文件結構

如果想要所有文件的小夥伴給我留言即可 

補充一點,由於在顯示模型的方法裡我加入了bboxHelper = new THREE.BoxHelper() 所以我們可以取得到模型的X Y Z三軸的尺寸也可以當作模型的長寬高 

上面是我整理給大家的,希望未來會對大家有幫助。

相關文章:

使用tangram.js函式庫如何實作js類別

利用js程式碼如何實作複製功能

使用JavaScript如何實作音訊播放功能

#

以上是在three.js中如何實作3D模型展示的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn