Modelo

  • EN
    • English
    • Español
    • Français
    • Bahasa Indonesia
    • Italiano
    • 日本語
    • 한국어
    • Português
    • ภาษาไทย
    • Pусский
    • Tiếng Việt
    • 中文 (简体)
    • 中文 (繁體)

Loading GLTF Models with Three.js

Jul 08, 2024

Three.js is a powerful JavaScript library for creating 3D graphics on the web. One of the most common tasks in 3D web development is loading 3D models into the scene. One of the most popular file formats for 3D models is GLTF, which is a flexible and efficient format for transmitting 3D models.

To load GLTF models into your Three.js scene, you can use the GLTFLoader provided by Three.js. Here's a step-by-step guide on how to use it:

1. First, make sure you have included the Three.js library in your HTML file. You can either download it and reference it locally, or use a CDN to include it in your project.

2. Next, you'll need to include the GLTFLoader script in your HTML file. You can do this by either downloading the script and including it locally, or using a CDN to include it in your project.

3. Once you have the required scripts included, you can start using the GLTFLoader in your JavaScript code. Here's an example of how to load a GLTF model into your scene:

```javascript

// Create a scene

const scene = new THREE.Scene();

// Create a camera

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

// Create a renderer

const renderer = new THREE.WebGLRenderer();

renderer.setSize(window.innerWidth, window.innerHeight);

document.body.appendChild(renderer.domElement);

// Load the GLTF model

const loader = new THREE.GLTFLoader();

loader.load(

'path/to/your/model.gltf',

(gltf) => {

scene.add(gltf.scene);

},

(xhr) => {

console.log((xhr.loaded / xhr.total * 100) + '% loaded');

},

(error) => {

console.error('An error happened', error);

}

);

// Position the camera

camera.position.z = 5;

// Create a simple animation loop

const animate = () => {

requestAnimationFrame(animate);

renderer.render(scene, camera);

};

animate();

```

In this example, we first create a scene, a camera, and a renderer. We then use the GLTFLoader to load the GLTF model into the scene. Once the model is loaded, we add it to the scene. Finally, we position the camera and create a simple animation loop to render the scene.

With these simple steps, you can easily load GLTF models into your Three.js scene and create stunning 3D web applications. Happy coding!

Recommend