three.js 载入 3D 模型的方法

three.js 载入 3D 模型的方法有很多种。以下是其中的一些:

1. OBJLoader模型加载器

import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js';

// 创建一个 OBJLoader 的实例
const loader = new OBJLoader();

// 载入模型文件,参数url是模型文件的路径,此处以 "example.obj" 为例
loader.load(
  'example.obj',

  // 加载完成后的回调函数
  function (obj) {
    // 当模型加载完成后会调用该函数

    // 将模型添加到场景中
    scene.add(obj);
  },

  // 正在加载模型时的回调函数
  function (xhr) {
    // 进度条代码,可以在此编写代码,传入 xhr.loaded 和 xhr.total,计算出加载进度
  },

  // 加载出错的回调函数
  function (err) {
    console.error('An error happened.');
  }
);

2. GLTFLoader模型加载器

import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';

// 创建一个 GLTFLoader 的实例
const loader = new GLTFLoader();

// 载入模型文件,参数url是模型文件的路径,此处以 "example.gltf" 为例
loader.load(
  'example.gltf',

  // 加载完成后的回调函数
  function (gltf) {
    // 当模型加载完成后会调用该函数

    // 将模型添加到场景中
    scene.add(gltf.scene);
  },

  // 正在加载模型时的回调函数
  function (xhr) {
    // 进度条代码,可以在此编写代码,传入 xhr.loaded 和 xhr.total,计算出加载进度
  },

  // 加载出错的回调函数
  function (err) {
    console.error('An error happened.');
  }
);

3. FBXLoader模型加载器

import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader.js';

// 创建一个 FBXLoader 的实例
const loader = new FBXLoader();

// 载入模型文件,参数url是模型文件的路径,此处以 "example.fbx" 为例
loader.load(
  'example.fbx',

  // 加载完成后的回调函数
  function (object) {
    // 当模型加载完成后会调用该函数

    // 将模型添加到场景中
    scene.add(object);
  },

  // 正在加载模型时的回调函数
  function (xhr) {
    // 进度条代码,可以在此编写代码,传入 xhr.loaded 和 xhr.total,计算出加载进度
  },

  // 加载出错的回调函数
  function (err) {
    console.error('An error happened.');
  }
);

4. ColladaLoader模型加载器

import { ColladaLoader } from 'three/examples/jsm/loaders/ColladaLoader.js';

// 创建一个 ColladaLoader 的实例
const loader = new ColladaLoader();

// 载入模型文件,参数url是模型文件的路径,此处以 "example.dae" 为例
loader.load(
  'example.dae',

  // 加载完成后的回调函数
  function (collada) {
    // 当模型加载完成后会调用该函数

    // 将模型添加到场景中
    scene.add(collada.scene);
  },

  // 正在加载模型时的回调函数
  function (xhr) {
    // 进度条代码,可以在此编写代码,传入 xhr.loaded 和 xhr.total,计算出加载进度
  },

  // 加载出错的回调函数
  function (err) {
    console.error('An error happened.');
  }
);

以上是几种常用类型的三维模型的加载器及其使用方法,可以根据需要使用相应的模型加载器来加载模型。

猜你喜欢

转载自blog.csdn.net/w418856/article/details/130573743