Three.js method to load 3D model

There are many ways to load 3D models in three.js. Here are some of them:

1. OBJLoader model loader

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 model loader

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 model loader

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 model loader

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.');
  }
);

The above are several commonly used types of 3D model loaders and their usage methods. You can use the corresponding model loader to load the model as needed.

Guess you like

Origin blog.csdn.net/w418856/article/details/130573743