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);

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

// 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;
  // 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; // Play the animation
}, undefined, function (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() {

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

  renderer.render(scene, camera);

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.