Blog>
Snippets

Creating and Animating a 3D Model

Load a 3D model using the GLTFLoader, create animations using the Three.js animation mixer, and play an animation in a loop.
// Import necessary Three.js components
const THREE = require('three');
const { GLTFLoader } = require('three/examples/jsm/loaders/GLTFLoader');

// Create a scene, camera, and renderer
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);
document.body.appendChild(renderer.domElement);

// Set up lights
const ambientLight = new THREE.AmbientLight(0xcccccc, 0.4);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(1, 1, 0).normalize();
scene.add(directionalLight);

// Position the camera
camera.position.z = 5;

// Load a GLTF model
const loader = new GLTFLoader();
let mixer;
loader.load('path_to_model/3d_model.gltf', function (gltf) {
  const model = gltf.scene;
  scene.add(model);
  // Create an AnimationMixer to handle the animations
  mixer = new THREE.AnimationMixer(model);
  const action = mixer.clipAction(gltf.animations[0]); // Get the first animation
  action.setLoop(THREE.LoopRepeat); // Set loop mode
  action.play(); // Play the animation
}, undefined, function (error) {
  console.error(error);
});
This piece of code sets up the basic elements of a Three.js scene including the scene itself, a camera, renderer, lights, and positions the camera. It then demonstrates how to load a 3D GLTF model using the GLTFLoader, create an AnimationMixer and play the first animation clip in a loop.
// Set up the animation loop
clock = new THREE.Clock();

function animate() {
  requestAnimationFrame(animate);

  // Update the AnimationMixer on each frame
  if (mixer) {
    const delta = clock.getDelta();
    mixer.update(delta);
  }

  renderer.render(scene, camera);
}

animate();
This code creates the animation loop, which is fired recursively by the requestAnimationFrame function. It updates the mixer on each frame, enabling animation of the model, and renders the scene using the given camera.