首頁 > 軟體

Vue整合three.js並載入glb、gltf、FBX、json模型的場景分析

2022-09-24 14:00:49

最近剛開始做的一個專案,後面有個模組要通過three.js實現3D的場景,因為之前也沒接觸過3D這塊,就提前學了一下,做個記錄。

先上幾個網址

ThreeJS官方:http://www.thingjs.com/guide/city2/ 

ThreeJS檔案:https://threejs.org/docs/index.html  

免費模型網:http://glbxz.com/err/search.php?keyword=%E5%85%8D%E8%B4%B9  

接下來就我做的一個demo開始 

安裝

npm i three
npm i three-orbitcontrols
npm i stats.js // 效能監測

元件中引入 

import * as THREE from 'three'
import * as Stats from 'stats.js'
import OrbitControls from 'three-orbitcontrols'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js'
import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader.js'

基本使用 

1.建立場景 

this.scene = new THREE.Scene();

2.相機 

this.camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 1000);
// 設定攝像機位置,相機方向逆X軸方向,傾斜向下看
this.camera.position.set(360, 360, 360);
// 指向場景中心
this.camera.lookAt(this.scene.position);

3. 渲染器

this.renderer = new THREE.WebGLRenderer({ antialias: true });
// 設定環境
this.renderer.setClearColor(new THREE.Color("#f1f9fb"));
// 設定場景大小
this.renderer.setSize(window.innerWidth / window.innerHeight);
// 渲染器開啟陰影效果
this.renderer.shadowMap.enabled = true;

4.建立紋理載入器 

this.textureLoader = new THREE.TextureLoader();

5.建立組合物件 

載入外部模型的時候,基本上都是一個組合物件,因為外部模型都是比較大的,把零散的模型組合到一塊便於操作,可以使用THREE.Group來操作一組物件,包括旋轉,縮放,移動等,裡面的子物件都會受到影響。THREE.Group繼承自THREE.Object3D物件,並且和THREE.Object3D物件沒有任何區別,僅僅是名字上的差異

this.groupBox = new THREE.Group();

6.新增座標軸,輔助判斷位置 

let axes = new THREE.AxesHelper(1000);
this.scene.add(axes);

7.點光源 

// 點光源
let point = new THREE.PointLight(0xffffff);
point.position.set(500, 300, 400); // 點光源位置
this.scene.add(point); // 點光源新增到場景中

8.環境光 

// 環境光
let ambient = new THREE.AmbientLight(0x999999);
this.scene.add(ambient);

9.效能監測 

//建立效能監測
this.stats = new Stats()
this.stats.showPanel(0) // 0: fps, 1: ms, 2: mb, 3+: custom
this.stats.domElement.style.position = 'absolute'; //絕對座標  this.stats.domElement.style.left = '0px';// (0,0)px,左上角  
this.stats.domElement.style.top = '0px';
$('#stats').appendChild(this.stats.domElement)

10.相機控制元件 

//建立相機控制元件
this.control = new OrbitControls(this.camera, this.renderer.domElement)
this.control.enableDamping = true
// 動態阻尼係數 就是滑鼠拖拽旋轉靈敏度,阻尼越小越靈敏
this.control.dampingFactor = 0.5;
// 是否可以縮放
this.control.enableZoom = true;
// 是否自動旋轉
this.control.autoRotate = false;
// 設定相機距離原點的最近距離
this.control.minDistance = 20;
// 設定相機距離原點的最遠距離
this.control.maxDistance = 1000;
// 是否開啟右鍵拖拽
this.control.enablePan = true;
// 上下翻轉的最大角度
this.control.maxPolarAngle = 1.5;
// 上下翻轉的最小角度
this.control.minPolarAngle = 0.0;
// 是否可以旋轉
this.enableRotate = true;

11.渲染canvas到容器 

$('#container').appendChild(this.renderer.domElement);

12.載入glb、gltf模型 

loadGlbModel() {
  const loader = new GLTFLoader()
  // const dracoLoader = new DRACOLoader()
  // dracoLoader.setDecoderPath('/draco/')
  // dracoLoader.preload()
  // loader.setDRACOLoader(dracoLoader)
  loader.load(`${this.publicPath}model/12OJJ6MOWT722N61Z5N92KA9C.glb`, (gltf) => {
    console.log(gltf, 'gltf----->>>')
    gltf.scene.scale.set(100,100,100)  //  設定模型大小縮放
    gltf.scene.position.set(0,0,0)
    let axis = new THREE.Vector3(0,1,0);//向量axis
    gltf.scene.rotateOnAxis(axis,Math.PI/2);
    //繞axis軸逆旋轉π/16
    gltf.scene.rotateOnAxis(axis,Math.PI/-20);
    gltf.scene.rotateOnAxis(axis,Math.PI/50);
    // gltf.rotateY(Math.PI / 2);
    // this.groupBox.add(gltf);
    this.scene.add(gltf.scene)
  }, (xhr) => {
      console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
  }, (error) => {
      console.error(error)
  })
},

13.載入FBX模型 

//  載入 FBX 模型
loadFbxModel() {
  const loader = new FBXLoader();
  loader.load(`${this.publicPath}model/glbxz.com6031.FBX`, object => {//載入路徑fbx檔案
    console.log(object, 'object----->>>')
    object.traverse( child => {
      if ( child.isMesh ){
        child.castShadow = true;
        child.receiveShadow = true;
      }
    });
    this.scene.add(object);//模型
  })
},

14.載入json模型 

//載入 JSON格式 模型
loadJsonModel() {
  //設定相機位置
  this.camera.position.z = 130
  this.camera.position.y = 80
  const loader = new THREE.ObjectLoader()
  loader.load(`${this.publicPath}model/xxxx.json`, json => {
    //處理載入模型為黑色問題
    json.traverse(child => {
      if (child.isMesh) {
        child.material.emissive = child.material.color
        child.material.emissiveMap = child.material.map
      }
    })
    this.scene.add(group)
  }, xhr => {
    // called while loading is progressing
    console.log(`${( xhr.loaded / xhr.total * 100 )}% loaded`);
  }, error => {
    // called when loading has errors
    console.error('An error happened', error);
  })
},

15.建立材質 

// 建立材質
createMaterial() {
  // 建立三維用到的材質
  /**
   * 
   * MeshBasicMaterial: 網格基礎材質
   * MeshDepthMaterial: 網格深度材質
   * MeshNormalMaterial: 網格法向材質
   * MeshLambertMaterial: 網格Lambert 材質
   * MeshPhongMaterial: 網格 Phong式材質
   * MeshStandardMaterial: 網格標準材質
   * MeshPhysicalMaterial: 網格物理材質
   * MeshToonMaterial: 網格卡通材質
   * ShadowMaterial: 陰影材質
   * ShaderMaterial: 著色器材質
   * LineBasicMaterial: 直線基礎材質
   * LineDashMaterial: 虛線材質
   */
  // 外牆
  let wallMaterial = new THREE.MeshLambertMaterial({ color: 0x00ffff });
  let wallGeo = new THREE.BoxGeometry(439 + 2 + 2, 120, 376.5 + 2 + 2); // 建立幾何體
  let wallMesh = new THREE.Mesh(wallGeo, wallMaterial);
  wallMesh.position.set(0, 60, 0); //(0, 60, -14.95);
  this.scene.add(wallMesh) // 新增結果到場景中
  // 內牆
  let wallInnerMaterial = new THREE.MeshLambertMaterial({
    color: 0x2d1bff,
  });
  let wallInnerGeo = new THREE.BoxGeometry(439, 120, 376.5); //(270, 120, 390);
  let wallInnerMesh = new THREE.Mesh(wallInnerGeo, wallInnerMaterial);
  wallInnerMesh.position.set(0, 60, 0); //(0, 60, -14.95);
  this.scene.add(wallInnerMesh)  // 新增結果到場景中
  // 門
  let doorTexture = this.textureLoader.load(
    require("../../../../assets/img/1.png") // 暫時注掉
  );
  let boxTextureMaterial = new THREE.MeshStandardMaterial({
    map: doorTexture,
    metalness: 0.2,
    roughness: 0.07,
    side: THREE.DoubleSide,
  });
  //let doorInnerMaterial = new THREE.MeshLambertMaterial({color: 0x2D1BFF});
  let doorGeo = new THREE.BoxGeometry(2, 80, 74.5);
  let doorMesh = new THREE.Mesh(doorGeo, boxTextureMaterial);
  doorMesh.position.set(-220.5, 40, 0);
  this.scene.add(doorMesh);  // 新增結果到場景中
 
  /**
   *  threeBSP - 參照還有問題
   */
  // //轉BSP
  // let wallBSP = new ThreeBSP(wallMesh);
  // let wallInnerBSP = new ThreeBSP(wallInnerMesh);
  // let doorBSP = new ThreeBSP(doorMesh);
  // // let window1BSP = new ThreeBSP(this.createWindowRight());
  // //let window2BSP = new ThreeBSP(this.createWindowRight());// createWindowLeft
  // let wallResultBSP = wallBSP.subtract(wallInnerBSP);
  // wallResultBSP = wallResultBSP.subtract(doorBSP);
  // // wallResultBSP = wallResultBSP.subtract(window1BSP);
  // //wallResultBSP = wallResultBSP.subtract(window2BSP);
  // let wallResultMesh = wallResultBSP.toMesh();
 
  // //轉換後的Mesh設定屬性
  // let wallTexture = this.textureLoader.load(require("../../../../assets/img/3.jpg")); // 暫時注掉
  // let wallTextureMaterial = new THREE.MeshStandardMaterial({
  //   map: wallTexture,
  //   metalness: 0.2,
  //   roughness: 0.07,
  //   side: THREE.DoubleSide,
  // });
  // let wallInnerTexture = this.textureLoader.load(
  //   require("../../../../assets/img/6.jpg") // 暫時注掉
  // );
  // let wallInnerTextureMaterial = new THREE.MeshStandardMaterial({
  //   map: wallInnerTexture,
  //   metalness: 0.2,
  //   roughness: 0.07,
  //   side: THREE.DoubleSide,
  // });
  // let wallResultMeshMaterial = [];
  // wallResultMeshMaterial.push(wallTextureMaterial);
  // wallResultMeshMaterial.push(wallInnerTextureMaterial);
  // //wallResultMeshMaterial.push(boxTextureMaterial);
  // wallResultMesh.material = wallResultMeshMaterial;
 
  // // console.log(wallResultMesh.geometry.faces, 112233);
  // wallResultMesh.geometry.faces.forEach((item, i) => {
  //   if (i < 160) {
  //     item.materialIndex = 0;
  //   } else {
  //     item.materialIndex = 1;
  //   }
  // });
 
  // wallResultMesh.geometry.computeFaceNormals();
  // wallResultMesh.geometry.computeVertexNormals();
  // //新增結果到場景中
  // this.scene.add(wallResultMesh);
},

16.進行渲染 

render() {
  let animate = () => {
    //迴圈呼叫函數
    this.clearAnim = requestAnimationFrame(animate)
    //更新相機控制元件
    this.control.update()
    // 更新效能外掛
    this.stats.update()
    //渲染介面
    this.renderer.render(this.scene, this.camera)
  }
  animate()
}

17.為模型繫結事件 

這裡以點選事件為例 

this.renderer.domElement.addEventListener('click', this.modelMouseClick, false)
// 模型的點選事件
modelMouseClick( event ) {
  var raycaster = new THREE.Raycaster();
  var mouse = new THREE.Vector2();
  // 將滑鼠位置歸一化為裝置座標。x 和 y 方向的取值範圍是 (-1 to +1)
  mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
  mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
  raycaster.setFromCamera(mouse, this.camera);
  const intersects = raycaster.intersectObjects(this.scene.children);
  // 根據它來判斷點選的什麼,length為0即沒有點選到模型
  console.log(intersects, 'intersects----->>>')
}

完整程式碼 

<template>
  <div id="import-template">
    <!-- 放效能監測的容器 -->
    <div id="stats"></div>
    <!-- 3D模型容器 -->
    <div id="container"></div>
  </div>
</template>
 
<script>
// import '@/utils/ThreeBSP.js' // 不可以這麼引
import * as THREE from 'three'
import * as Stats from 'stats.js'
// import * as dat from 'dat.gui'
import OrbitControls from 'three-orbitcontrols'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js'
import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader.js'
const $ = name => document.querySelector(name)
 
export default {
  data() {
    return {
      scene: null, // 場景
      camera: null, // 照相機
      renderer: null, // 渲染器
      mesh: null, // 網格
      textureLoader: null, // 紋理載入器
      mixer: null,
      groupBox: null,
      stats: null, // 效能監測
      control: null, // 相機控制元件
      publicPath: process.env.BASE_URL,
      clearAnim: null,
      clock: null
    }
  },
  created() {
    // this.init()
  },
  mounted() {
    this.init()
  },
  destroyed() {
    cancelAnimationFrame(this.clearAnim)  // 清除requestAnimationFrame
    this.renderer.domElement.removeEventListener('click', this.modelMouseClick, false)
    this.scene = null, // 場景
    this.camera = null, // 照相機
    this.renderer = null, // 渲染器
    this.mesh = null, // 網格
    this.textureLoader = null, // 紋理載入器
    this.mixer = null,
    this.groupBox = null,
    this.stats = null, // 效能監測
    this.control = null, // 相機控制元件
    this.publicPath = process.env.BASE_URL,
    this.clock = null
  },
  methods: {
    //初始化
    init() {
      // 場景
      this.scene = new THREE.Scene();
      // 1.2 相機
      this.camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 1000);
      // 設定攝像機位置,相機方向逆X軸方向,傾斜向下看
      this.camera.position.set(360, 360, 360);
      //this.camera.position.set(-20, 40 ,30)
      // 指向場景中心
      this.camera.lookAt(this.scene.position);
      // 1.3 渲染器
      this.renderer = new THREE.WebGLRenderer({ antialias: true });
      // 建立紋理載入器
      this.textureLoader = new THREE.TextureLoader();
      // 建立一個組合物件
      this.groupBox = new THREE.Group();
      // 新增座標軸,輔助判斷位置
      let axes = new THREE.AxesHelper(1000);
      this.scene.add(axes);
      // 設定環境
      this.renderer.setClearColor(new THREE.Color("#f1f9fb"));
      // 設定場景大小
      this.renderer.setSize(
        $('#container').getBoundingClientRect().width,
        $('#container').getBoundingClientRect().height
      );
      // 渲染器開啟陰影效果
      this.renderer.shadowMap.enabled = true;
      // 點光源
      let point = new THREE.PointLight(0xffffff);
      point.position.set(500, 300, 400); // 點光源位置
      this.scene.add(point); // 點光源新增到場景中
      // 環境光
      let ambient = new THREE.AmbientLight(0x999999);
      this.scene.add(ambient);
 
      //建立效能監測
      this.stats = new Stats()
      this.stats.showPanel(0) // 0: fps, 1: ms, 2: mb, 3+: custom
      this.stats.domElement.style.position = 'absolute'; //絕對座標  
      this.stats.domElement.style.left = '0px';// (0,0)px,左上角  
      this.stats.domElement.style.top = '0px';
      $('#stats').appendChild(this.stats.domElement)
 
      // 渲染div到canvas
      $('#container').appendChild(this.renderer.domElement);
 
      //建立相機控制元件
      this.control = new OrbitControls(this.camera, this.renderer.domElement)
      this.control.enableDamping = true
      // 動態阻尼係數 就是滑鼠拖拽旋轉靈敏度,阻尼越小越靈敏
      this.control.dampingFactor = 0.5;
      // 是否可以縮放
      this.control.enableZoom = true;
      // 是否自動旋轉
      this.control.autoRotate = false;
      // 設定相機距離原點的最近距離
      this.control.minDistance = 20;
      // 設定相機距離原點的最遠距離
      this.control.maxDistance = 1000;
      // 是否開啟右鍵拖拽
      this.control.enablePan = true;
      // 上下翻轉的最大角度
      this.control.maxPolarAngle = 1.5;
      // 上下翻轉的最小角度
      this.control.minPolarAngle = 0.0;
      // 是否可以旋轉
      this.enableRotate = true;
      this.loadGlbModel(); // 載入 glb、gltf模型
      // this.loadFbxModel() // 載入 FBX 模型
      // this.loadJsonModel() // 載入 json 模型
      // this.createMaterial() // 建立材質
      // 最後進行渲染
      this.render()
    },
    // 最後的渲染
    render() {
      let animate = () => {
        //迴圈呼叫函數
        this.clearAnim = requestAnimationFrame(animate)
        //更新相機控制元件
        this.control.update()
        // 更新效能外掛
        this.stats.update()
        //渲染介面
        this.renderer.render(this.scene, this.camera)
      }
      animate()
      //  為模型繫結點選事件
      this.renderer.domElement.addEventListener('click', this.modelMouseClick, false)
    },
    // 建立材質
    createMaterial() {
      // 建立三維用到的材質
      /**
       * 
       * MeshBasicMaterial: 網格基礎材質
       * MeshDepthMaterial: 網格深度材質
       * MeshNormalMaterial: 網格法向材質
       * MeshLambertMaterial: 網格Lambert 材質
       * MeshPhongMaterial: 網格 Phong式材質
       * MeshStandardMaterial: 網格標準材質
       * MeshPhysicalMaterial: 網格物理材質
       * MeshToonMaterial: 網格卡通材質
       * ShadowMaterial: 陰影材質
       * ShaderMaterial: 著色器材質
       * LineBasicMaterial: 直線基礎材質
       * LineDashMaterial: 虛線材質
       */
      // 外牆
      let wallMaterial = new THREE.MeshLambertMaterial({ color: 0x00ffff });
      let wallGeo = new THREE.BoxGeometry(439 + 2 + 2, 120, 376.5 + 2 + 2); // 建立幾何體
      let wallMesh = new THREE.Mesh(wallGeo, wallMaterial);
      wallMesh.position.set(0, 60, 0); //(0, 60, -14.95);
      this.scene.add(wallMesh)
      // 內牆
      let wallInnerMaterial = new THREE.MeshLambertMaterial({
        color: 0x2d1bff,
      });
      let wallInnerGeo = new THREE.BoxGeometry(439, 120, 376.5); //(270, 120, 390);
      let wallInnerMesh = new THREE.Mesh(wallInnerGeo, wallInnerMaterial);
      wallInnerMesh.position.set(0, 60, 0); //(0, 60, -14.95);
      this.scene.add(wallInnerMesh)
      // 門
      let doorTexture = this.textureLoader.load(
        require("../../../../assets/img/1.png") // 暫時注掉
      );
      let boxTextureMaterial = new THREE.MeshStandardMaterial({
        map: doorTexture,
        metalness: 0.2,
        roughness: 0.07,
        side: THREE.DoubleSide,
      });
      //let doorInnerMaterial = new THREE.MeshLambertMaterial({color: 0x2D1BFF});
      let doorGeo = new THREE.BoxGeometry(2, 80, 74.5);
      let doorMesh = new THREE.Mesh(doorGeo, boxTextureMaterial);
      doorMesh.position.set(-220.5, 40, 0);
      this.scene.add(doorMesh);
 
      /**
       *  threeBSP - 參照還有問題
       */
      // //轉BSP
      // let wallBSP = new ThreeBSP(wallMesh);
      // let wallInnerBSP = new ThreeBSP(wallInnerMesh);
      // let doorBSP = new ThreeBSP(doorMesh);
      // // let window1BSP = new ThreeBSP(this.createWindowRight());
      // //let window2BSP = new ThreeBSP(this.createWindowRight());// createWindowLeft
      // let wallResultBSP = wallBSP.subtract(wallInnerBSP);
      // wallResultBSP = wallResultBSP.subtract(doorBSP);
      // // wallResultBSP = wallResultBSP.subtract(window1BSP);
      // //wallResultBSP = wallResultBSP.subtract(window2BSP);
      // let wallResultMesh = wallResultBSP.toMesh();
 
      // //轉換後的Mesh設定屬性
      // let wallTexture = this.textureLoader.load(require("../../../../assets/img/3.jpg")); // 暫時注掉
      // let wallTextureMaterial = new THREE.MeshStandardMaterial({
      //   map: wallTexture,
      //   metalness: 0.2,
      //   roughness: 0.07,
      //   side: THREE.DoubleSide,
      // });
      // let wallInnerTexture = this.textureLoader.load(
      //   require("../../../../assets/img/6.jpg") // 暫時注掉
      // );
      // let wallInnerTextureMaterial = new THREE.MeshStandardMaterial({
      //   map: wallInnerTexture,
      //   metalness: 0.2,
      //   roughness: 0.07,
      //   side: THREE.DoubleSide,
      // });
      // let wallResultMeshMaterial = [];
      // wallResultMeshMaterial.push(wallTextureMaterial);
      // wallResultMeshMaterial.push(wallInnerTextureMaterial);
      // //wallResultMeshMaterial.push(boxTextureMaterial);
      // wallResultMesh.material = wallResultMeshMaterial;
 
      // // console.log(wallResultMesh.geometry.faces, 112233);
      // wallResultMesh.geometry.faces.forEach((item, i) => {
      //   if (i < 160) {
      //     item.materialIndex = 0;
      //   } else {
      //     item.materialIndex = 1;
      //   }
      // });
 
      // wallResultMesh.geometry.computeFaceNormals();
      // wallResultMesh.geometry.computeVertexNormals();
      // //新增結果到場景中
      // this.scene.add(wallResultMesh);
    },
    // 載入 GLTF 模型
    loadGlbModel() {
      const loader = new GLTFLoader()
      // const dracoLoader = new DRACOLoader()
      // dracoLoader.setDecoderPath('/draco/')
      // dracoLoader.preload()
      // loader.setDRACOLoader(dracoLoader)
      loader.load(`${this.publicPath}model/12OJJ6MOWT722N61Z5N92KA9C.glb`, (gltf) => {
        console.log(gltf, 'gltf----->>>')
        gltf.scene.scale.set(100,100,100)  //  設定模型大小縮放
        gltf.scene.position.set(0,0,0)
        let axis = new THREE.Vector3(0,1,0);//向量axis
        gltf.scene.rotateOnAxis(axis,Math.PI/2);
        //繞axis軸逆旋轉π/16
        gltf.scene.rotateOnAxis(axis,Math.PI/-20);
        gltf.scene.rotateOnAxis(axis,Math.PI/50);
        // gltf.rotateY(Math.PI / 2);
        // this.groupBox.add(gltf);
        this.scene.add(gltf.scene)
      }, (xhr) => {
          console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
      }, (error) => {
          console.error(error)
      })
    },
    //  載入 FBX 模型
    loadFbxModel() {
      const loader = new FBXLoader();
      loader.load(`${this.publicPath}model/glbxz.com6031.FBX`, object => {//載入路徑fbx檔案
        console.log(object, 'object----->>>')
        object.traverse( child => {
          if ( child.isMesh ){
            child.castShadow = true;
            child.receiveShadow = true;
          }
        });
        this.scene.add(object);//模型
      })
    },
    //載入 JSON格式 模型
    loadJsonModel() {
      //設定相機位置
      this.camera.position.z = 130
      this.camera.position.y = 80
      const loader = new THREE.ObjectLoader()
      loader.load(`${this.publicPath}model/xxxx.json`, json => {
        //處理載入模型為黑色問題
        json.traverse(child => {
          if (child.isMesh) {
            child.material.emissive = child.material.color
            child.material.emissiveMap = child.material.map
          }
        })
        this.scene.add(group)
      }, xhr => {
        // called while loading is progressing
        console.log(`${( xhr.loaded / xhr.total * 100 )}% loaded`);
      }, error => {
        // called when loading has errors
        console.error('An error happened', error);
      })
    },
    // 模型的點選事件
    modelMouseClick( event ) {
      var raycaster = new THREE.Raycaster();
      var mouse = new THREE.Vector2();
      // 將滑鼠位置歸一化為裝置座標。x 和 y 方向的取值範圍是 (-1 to +1)
      mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
      mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
      raycaster.setFromCamera(mouse, this.camera);
      const intersects = raycaster.intersectObjects(this.scene.children);
      // 根據它來判斷點選的什麼,length為0即沒有點選到模型
      console.log(intersects, 'intersects----->>>')
    }
  }
}
</script>
<style scoped>
#import-template {
  width: 100%;
  height: 100%;
}
#stats {
  width: 100%;
  height: 50px;
  position: relative;
}
#container {
  width: 100%;
  height: calc(100% - 50px);
}
</style>

效果 

  

最後再補充一下,有個threeBSP,,到現在還沒知道怎麼去參照,搞這個東西才兩天,很多還需要慢慢摸索 ,好像這個threBSP不支援npm裝,而且必須要引在THREE後面。。。慢慢再搞

<script src="https://johnson2heng.github.io/three.js-demo/lib/threebsp.js"></script>

 這個是threeBSP線上的包,如果向上面例子按需引入THREE,那應該怎麼去引這個包呢,, 

不斷學習中。。。

補充 

接上面的問題,【已解決】ThreeBSP引入問題 

見下篇博文three.js 利用uv和ThreeBSP製作一個快遞櫃功能

到此這篇關於Vue整合three.js,並載入glb、gltf、FBX、json模型的文章就介紹到這了,更多相關Vue整合three.js內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com