Vue 2中建立一个画布并加载GLTF格式的3D模型

279 阅读1分钟

在Vue 2中建立一个画布并加载GLTF格式的3D模型,你可以使用Three.js库来实现。

  1. 首先,在你的Vue项目中安装three库:
npm install three
  1. 在Vue组件中,添加画布并加载3D模型:
<template>
  <div ref="canvasContainer"></div>
</template>

<script>
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';

export default {
  mounted() {
    this.initCanvas();
  },
  methods: {
    initCanvas() {
      // 创建场景、相机和渲染器
      const scene = new THREE.Scene();
      const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
      const renderer = new THREE.WebGLRenderer();
      renderer.setSize(window.innerWidth, window.innerHeight);
      this.$refs.canvasContainer.appendChild(renderer.domElement);

      // 添加灯光
      const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
      scene.add(ambientLight);
      const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
      scene.add(directionalLight);

      // 加载GLTF模型
      const loader = new GLTFLoader();
      const modelPath = 'path_to_your_gltf_model.gltf';
      loader.load(modelPath, (gltf) => {
        const model = gltf.scene;
        scene.add(model);
      });

      // 设置相机位置
      camera.position.z = 5;

      // 动画渲染循环
      const animate = () => {
        requestAnimationFrame(animate);
        // 模型旋转
        if (model) {
          model.rotation.x += 0.01;
          model.rotation.y += 0.01;
        }
        renderer.render(scene, camera);
      };

      animate();
    },
  },
};
</script>

备注:

  • mounted钩子函数中调用initCanvas方法,确保在Vue组件加载后初始化画布。
  • 使用three库中的THREE对象来创建场景、相机、渲染器、灯光等。
  • 使用GLTFLoader加载器来加载GLTF格式的3D模型。请将modelPath替换为你实际的模型路径。
  • 通过model.rotation属性来实现模型的旋转效果,可以根据需求调整旋转角度。