VUE+Three.js引用外部模型

本文介绍如何使用Three.js加载和展示3D模型,并实现基本动画效果。通过安装three和three-orbitcontrols,设置环境光和方向光,配置透视相机,加载GLTF格式的3D模型,最终实现模型的渲染。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1,安装three 和 three-orbitcontrols

npm i -s three
npm i three-orbitcontrols

2,在public下面创建static放置模型文件

在这里插入图片描述文件目录

3,在页面引入three

import * as THREE from "three"; //引入Threejs
import {GLTFLoader} from "three/examples/jsm/loaders/GLTFLoader"; //模型加载器

4,初始化

 init() {
      let container = document.getElementById("container");//显示3D模型的容器
      this.scene = new THREE.Scene();
      this.scene.add(new THREE.AmbientLight(0x404040, 6)); //环境光
      this.light = new THREE.DirectionalLight(0xdfebff, 0.45); //从正上方(不是位置)照射过来的平行光,0.45的强度
      this.light.position.set(50, 200, 100);
      this.light.position.multiplyScalar(0.3);
      this.scene.add(this.light);
      /**
       * 相机设置
       */

      this.camera = new THREE.PerspectiveCamera(
          70,
          container.clientWidth / container.clientHeight,
          0.01,
          10
      );
      this.camera.position.z = 1;
      /**
       * 创建渲染器对象
       */
      this.renderer = new THREE.WebGLRenderer({alpha: true});
      this.renderer.setSize(container.clientWidth, container.clientHeight);
      container.appendChild(this.renderer.domElement);

    },

5,加载模型以及动画

 loadGltf() {
      let self = this;
      let loader = new GLTFLoader();
      //本地模型路径:public/static/mod/Xbot.glb
      loader.load("static/mod/Xbot.glb", function (gltf) {
        self.isLoading = false;//关闭载入中效果
        self.mesh = gltf.scene;
        self.mesh.scale.set(0.3, 0.3, 0.3);//设置大小比例
        self.mesh.position.set(0, 0, 0);//设置位置
        self.scene.add(self.mesh); // 将模型引入three、
        self.animate();
      });
    },
    animate() {
      if (this.mesh) {
        requestAnimationFrame(this.animate);
        // this.mesh.rotation.y += 0.004;//绕Y轴旋转0.004°
        this.renderer.render(this.scene, this.camera);
      }
    },

完整代码

<template>
  <div id="import-template">
    <div id="container">

    </div>
  </div>
</template>

<script>
import * as THREE from "three"; //引入Threejs
import {GLTFLoader} from "three/examples/jsm/loaders/GLTFLoader"; //模型加载器


export default {
  name: 'ImportTemplate',
  data() {
    return {
      scene: null,
      light: null,
      camera: null,
      renderer: null,
      mesh: null,
      group: null
    }
  },
  mounted() {
    this.init()
    this.loadGltf()
  },

  methods: {
    init() {
      let container = document.getElementById("container");//显示3D模型的容器
      this.scene = new THREE.Scene();
      this.scene.add(new THREE.AmbientLight(0x404040, 6)); //环境光
      this.light = new THREE.DirectionalLight(0xdfebff, 0.45); //从正上方(不是位置)照射过来的平行光,0.45的强度
      this.light.position.set(50, 200, 100);
      this.light.position.multiplyScalar(0.3);
      this.scene.add(this.light);
      /**
       * 相机设置
       */

      this.camera = new THREE.PerspectiveCamera(
          70,
          container.clientWidth / container.clientHeight,
          0.01,
          10
      );
      this.camera.position.z = 1;
      /**
       * 创建渲染器对象
       */
      this.renderer = new THREE.WebGLRenderer({alpha: true});
      this.renderer.setSize(container.clientWidth, container.clientHeight);
      container.appendChild(this.renderer.domElement);

    },
    loadGltf() {
      let self = this;
      let loader = new GLTFLoader();
      //本地模型路径:public/static/mod/Xbot.glb
      loader.load("static/mod/Xbot.glb", function (gltf) {
        self.isLoading = false;//关闭载入中效果
        self.mesh = gltf.scene;
        self.mesh.scale.set(0.3, 0.3, 0.3);//设置大小比例
        self.mesh.position.set(0, 0, 0);//设置位置
        self.scene.add(self.mesh); // 将模型引入three、
        self.animate();
      });
    },
    animate() {
      if (this.mesh) {
        requestAnimationFrame(this.animate);
        // this.mesh.rotation.y += 0.004;//绕Y轴旋转0.004°
        this.renderer.render(this.scene, this.camera);
      }
    },
  }
}
</script>

<style scoped>
#import-template {
  width: 1920px;
  height: 1080px;
}

#container {
  width: 500px;
  height: 500px;
  margin: 150px auto;
}
</style>

### 开源 Vue Three.js 实战项目 #### vue-threejsVue Bindings for Three.js vue-threejs 是一个用于将 Three.js 集成到 Vue 应用中的库,提供了绑定和工具来简化开发过程[^1]。此项目的 GitHub 地址为 [https://gitcode.com/gh_mirrors/vu/vue-threejs](https://gitcode.com/gh_mirrors/vu/vue-threejs),开发者可以在此找到详细的文档和支持资源。 ```javascript import * as THREE from 'three'; import { onMounted, ref } from 'vue'; export default { setup() { let camera; let renderer; let scene; onMounted(() => { // 初始化场景 scene = new THREE.Scene(); // 创建相机并设置位置 camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 ); camera.position.z = 5; // 设置渲染器尺寸并与页面适配 renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); // 添加几何体和材质 const geometry = new THREE.BoxGeometry(1, 1, 1); const material = new THREE.MeshBasicMaterial({ color: '#433F81', wireframe: true, }); const cube = new THREE.Mesh(geometry, material); scene.add(cube); function animate() { requestAnimationFrame(animate); // 动画逻辑 cube.rotation.x += 0.01; cube.rotation.y += 0.01; renderer.render(scene, camera); } animate(); }); return {}; }, }; ``` 上述代码展示了如何利用 `vue-threejs` 将 Three.js 整合进 Vue 组件中,并实现了一个简单的旋转立方体效果。 #### icegl-three-vue-tres 另一个值得关注的是名为 **icegl-three-vue-tres** 的开源项目,它同样是一个基于 VueThree.js 构建的应用程序实例[^2]。虽然具体的细节可能有所不同,但是这个项目也提供了一种很好的方式去理解和应用这两个强大的前端技术栈组合在一起的工作流程。 对于加载复杂的 3D 模型文件(如 `.gltf`),可以通过如下方法完成: ```javascript // 加载GLTF模型 loadGLTF() { const loader = new GLTFLoader() loader.load('./models/machineRoom.gltf', (result) => { console.log(result.scene.children); result.scene.traverse((child) => { if (child.isMesh) child.castShadow = true; }); this.scene.add(result.scene) }) } ``` 这段代码片段说明了怎样使用 `GLTFLoader` 来异步加载外部的 glTF 文件,并将其添加至当前场景中[^3]。 为了提高大模型加载效率还可以引入 Draco 压缩算法支持,具体做法是在加载前先解码压缩过的二进制数据流(ArrayBuffer)[^4]: ```javascript const dracoLoader = new DRACOLoader(); dracoLoader.setDecoderPath('https://www.gstatic.com/draco/versioned/decoders/'); loader.setDRACOLoader(dracoLoader); loader.load(url, onLoadCallback); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值