THREEJS Animation

ASHABB ReactJS & ThreeJS
5 min readJul 1, 2023

--

Three.js Mesh Animation: Adding Movement to 3D Objects

Photo by FRANCESCO TOMMASINI on Unsplash

Description

Three.js allows beginners to easily create captivating 3D graphics and animations on the web. With mesh animation, you can bring your 3D objects to life by adding movement and changing their appearance. Techniques like keyframe animation and morph targets enable smooth transitions and interactive experiences. Three.js provides a beginner-friendly API, tutorials, and documentation to guide you. Explore the exciting world of mesh animation with Three.js and make your web projects visually stunning and interactive. Get ready to unleash your creativity and take your designs to the next level with Three.js mesh animation.

1. Title

2. Description

3. Snippet

4. Explaination

5. Full code

6. Output

7. Summary

8. Next and Previous Blog

3. Snippet

 /*-------------box geometry-------------*/
const demoMeshGeometry = new THREE.BoxGeometry(10, 10, 10);
const demoMeshMaterial = new THREE.MeshBasicMaterial({
color: '#ff0',
});
demoMesh = new THREE.Mesh(demoMeshGeometry, demoMeshMaterial);
demoMesh.position.set(0, 5, 0)
scene.add(demoMesh)

4. Explaination

The code snippet creates a box-shaped mesh using Three.js. Here’s a simplified explanation:

- `demoMeshGeometry` defines the geometry of the mesh, specifying its size as 10 units in width, height, and depth.
- `demoMeshMaterial` defines the material used for the mesh, setting its color to yellow (`’#ff0'`).
- `demoMesh` is the actual mesh object created by combining the geometry and material.
- The position of the mesh is set to `(0, 5, 0)`, meaning it will be placed at the center of the scene, 5 units above the ground.
- Finally, the mesh is added to the scene, making it visible in the 3D environment.

In summary, this code creates a simple yellow box mesh with a size of 10 units and positions it at the center of the scene, slightly above the ground.

        let time = Date.now()

function animate() {
const currentTime = Date.now()
const deltaTime = currentTime - time
time = currentTime


demoMesh.rotation.y += 0.001 * deltaTime
demoMesh.rotation.x += 0.001 * deltaTime
requestAnimationFrame(animate)
renderer.render(scene, camera);
}In the given code snippet, we have the following lines:

The code snippet sets up an animation loop using Three.js. Here’s a simplified explanation:

- The variable `time` is initialized with the current timestamp using `Date.now()`. It will be used to calculate the time difference between animation frames.
- The `animate` function is defined, which will be called recursively to update and render the scene.
- Inside the `animate` function, the current timestamp is stored in the `currentTime` variable, and the time difference (`deltaTime`) between the current and previous frames is calculated.
- The `demoMesh` object’s rotation is updated by incrementing the `y` and `x` rotation angles with a small value multiplied by `deltaTime`. This creates a smooth rotation effect over time.
- The `requestAnimationFrame` function is called to request the browser to call `animate` again for the next frame, creating an animation loop.
- Finally, the renderer is used to render the updated scene with the camera’s perspective.

In summary, this code sets up a continuous animation loop that rotates the `demoMesh` object gradually on the `y` and `x` axes. The rotation speed is determined by the elapsed time between frames, resulting in a smooth and dynamic animation.

5. Full code


<!DOCTYPE html>
<html lang="en">

<head>
<title>three.js - Boilerplate</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link type="text/css" rel="stylesheet" href="/cdn/editor/css/main.css">

<style>
body {
background-color: grey
}

html,
body {
margin: 0;
height: 100%;
}

#c {
width: 100%;
height: 100%;
display: block;
color: rgb(40, 63, 141);
}
</style>

</head>

<body>
<canvas id="c"></canvas>

<script type="importmap">
{
"imports": {
"three": "./threeJS/build/three.module.js"
}
}
</script>

<script type="module">

import * as THREE from 'three';
import { OrbitControls } from './threeJS/examples/jsm/controls/OrbitControls.js';
import * as DAT from './threeJS/newadded/DatGUI.js';

var canvas, renderer, scene, camera, controls, demoMesh;
// var gui = new DAT.GUI();

function init() {

canvas = document.querySelector('#c');

renderer = new THREE.WebGLRenderer({ canvas });
renderer.setSize(window.innerWidth, window.innerHeight);

scene = new THREE.Scene();
scene.background = new THREE.Color('black');
const cubeTextureLoader = new THREE.CubeTextureLoader()

scene.background = new THREE.Color('green');

const ambientLight = new THREE.AmbientLight(0xffffff, 0.7)
scene.add(ambientLight)
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
scene.add(directionalLight);

camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.y = 10;
camera.position.z = 25;


controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.6;
controls.screenSpacePanning = false;
controls.update();

/*-----------------texture-------------------*/
var map = new THREE.TextureLoader().load('./static/image/land.jpg');

const floorGeometry = new THREE.PlaneGeometry(50, 50, 128, 128);
const floorMaterial = new THREE.MeshStandardMaterial({
color: '#777777',
metalness: 0.2,
roughness: 0.6,
envMapIntensity: 0.5,
side: THREE.DoubleSide,
map: map

});
const floor = new THREE.Mesh(floorGeometry, floorMaterial)
floor.receiveShadow = true;
floor.rotation.x = - Math.PI * 0.5;
floor.position.set(0, 0, 0);
scene.add(floor);

/*-------------box geometry-------------*/
const demoMeshGeometry = new THREE.BoxGeometry(10, 10, 10);
const demoMeshMaterial = new THREE.MeshBasicMaterial({
color: '#ff0',
});
demoMesh = new THREE.Mesh(demoMeshGeometry, demoMeshMaterial);
demoMesh.position.set(0, 5, 0)
scene.add(demoMesh)
}


let time = Date.now()

function animate() {
const currentTime = Date.now()
const deltaTime = currentTime - time
time = currentTime


demoMesh.rotation.y += 0.001 * deltaTime
demoMesh.rotation.x += 0.001 * deltaTime
requestAnimationFrame(animate)
renderer.render(scene, camera);
}
init()
animate();
</script>
</body>

</html>

6. Output

7. Summary

what we learned in this blog

In today’s blog, we learned about Three.js mesh animation. We explored how to create a basic scene with a rotating mesh using the BoxGeometry and MeshBasicMaterial. We also implemented a simple animation loop using requestAnimationFrame and calculated the time difference between frames to achieve smooth animation. By adjusting the rotation angles of the mesh over time, we created an engaging and dynamic animation effect. This blog served as an introduction to mesh animation in Three.js, providing beginners with a foundation to start experimenting and creating their own interactive 3D animations.

Photo by Howie R on Unsplash

--

--