DEV Community

Cover image for Learning Three.js in 2024 🚀
Ankita Kanchan
Ankita Kanchan

Posted on

Learning Three.js in 2024 🚀

I had the chance to dive into some web development where I wanted to add interactive 3D elements that could move and react to certain triggers. Naturally, this led me to explore Three.js — a super popular library for rendering 3D graphics on the web.

While learning Three.js, I went through a ton of blogs, tutorials, and resources, and I thought, “Why not summarize my journey and share a really cool example?” So, if you’re someone who wants to get started with Three.js, I’ve put together this guide just for you.

As we step into 2024, the need for immersive and interactive 3D experiences is skyrocketing. Whether it’s for e-commerce sites showing 3D models of products, educational platforms using 3D simulations, or even games — 3D technology is transforming the way we engage with digital content. And the best part? With Three.js, creating these experiences is easier than ever!

In this guide, I’ll take you step-by-step through Three.js, and by the end, you’ll have built a 3D scene with a floating astronaut in space. 🧑‍🚀🌌

Ready to dive in? Let’s get started!

Why Learn Three.js in 2024? 🔥

Three.js provides a simple yet powerful way to bring these 3D experiences to the web. Here’s why learning Three.js is a fantastic idea in 2024:

  1. WebXR and WebGL: Virtual reality (VR) and augmented reality (AR) on the web are growing, and Three.js is WebXR-ready.
  2. Cross-Browser Support: It works seamlessly across modern browsers, including mobile ones.
  3. Lightweight 3D Creation: No need to learn complex WebGL. Three.js makes 3D creation as easy as writing JavaScript.
  4. Growing Community: With more than a decade of active development, the library has an ever-growing collection of plugins and examples.

Setting Up: Your First Three.js Scene

Let’s start with the basics. The magic of Three.js starts with three core concepts: Scene, Camera, and Renderer. If you understand these, you’re already halfway there!

1. The Scene 🏙️

Think of the scene as your 3D canvas. It contains all the objects, lights, and cameras needed to create the final 3D rendering.



const scene = new THREE.Scene();


Enter fullscreen mode Exit fullscreen mode

2. The Camera 📸

The camera is your “viewpoint” into the 3D world. In 2024, most developers use PerspectiveCamera, which simulates how human eyes see the world.



const camera = new THREE.PerspectiveCamera(
  75, // Field of view
  window.innerWidth / window.innerHeight, // Aspect ratio
  0.1, // Near clipping plane
  1000 // Far clipping plane
);
camera.position.z = 5; // Move the camera back so we can see the objects


Enter fullscreen mode Exit fullscreen mode

3. The Renderer 🎨

The renderer converts the 3D scene and camera into a 2D image for the browser to display. In 2024, we typically use WebGLRenderer, which is optimized for modern browsers.



const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement); 
// Adds the canvas to the webpage


Enter fullscreen mode Exit fullscreen mode

4. Creating a Simple 3D Object: A Cube 🟩

Let’s create our first 3D object: a cube. We define its geometry, give it a material, and combine them into a mesh.



const geometry = new THREE.BoxGeometry(); // Define the shape (cube)
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
 // Apply a green color to the cube
const cube = new THREE.Mesh(geometry, material); 
// Combine the geometry and material into a 3D mesh
scene.add(cube); // Add the cube to the scene


Enter fullscreen mode Exit fullscreen mode

5. Animating the Cube 🌀

3D is all about movement! Let’s make our cube rotate. To do this, we create an animation loop using requestAnimationFrame, which ensures smooth 60fps rendering.



function animate() {
  requestAnimationFrame(animate); // Keep looping the function for continuous animation

  cube.rotation.x += 0.01; // Rotate cube on the X axis
  cube.rotation.y += 0.01; // Rotate cube on the Y axis
renderer.render(scene, camera); // Render the scene from the camera's perspective
}
animate(); // Start the animation loop


Enter fullscreen mode Exit fullscreen mode

Putting It All Together:



const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
function animate() {
  requestAnimationFrame(animate);
  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;
  renderer.render(scene, camera);
}
animate();


Enter fullscreen mode Exit fullscreen mode

Congrats! 🎉 You’ve now set up the basics of a 3D world ! 🥳

Adding Objects to the Scene 🛠️

Now that we have a scene, camera, and renderer, it’s time to add some 3D objects! We’ll start with something simple: a rotating cube.



const geometry = new THREE.BoxGeometry(); // Defines the shape
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); 
// Adds color to the shape
const cube = new THREE.Mesh(geometry, material); 
// Combines the shape and color
scene.add(cube); // Adds the cube to the scene


Enter fullscreen mode Exit fullscreen mode

Adding Animation:

Now let’s animate the cube so it spins! Real-time graphics need smooth animations, and we can achieve that with requestAnimationFrame.



function animate() {
  requestAnimationFrame(animate); // Keep looping through this function

  cube.rotation.x += 0.01; // Rotate the cube around the X axis
  cube.rotation.y += 0.01; // Rotate the cube around the Y axis

renderer.render(scene, camera); // Render the scene from the perspective of the camera

}
animate(); // Start the animation loop



Enter fullscreen mode Exit fullscreen mode

And boom 💥 — You’ve just created your first animated 3D object in Three.js!

Taking It Up a Notch

Lights, Materials, and Shadows 🌟

3D graphics are nothing without light. The more realistic the lighting, the more impressive your 3D world becomes. Let’s explore:

Adding Lights 💡

Without light, even the best 3D models will look flat and lifeless. In Three.js, there are several types of lights:

  • AmbientLight: Provides soft global lighting that illuminates all objects equally.
  • DirectionalLight: Simulates sunlight, casting parallel light rays in a specific direction.


const ambientLight = new THREE.AmbientLight(0x404040, 2);
 // Soft light to brighten the scene
scene.add(ambientLight);

const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(1, 1, 1).normalize(); 
// Light from top-right corner
scene.add(directionalLight);



Enter fullscreen mode Exit fullscreen mode

Better Materials for Realism 🎨

MeshStandardMaterial is the go-to material for creating objects that look realistic.



const material = new THREE.MeshStandardMaterial({ color: 0xff0051, metalness: 0.6, roughness: 0.4 });


Enter fullscreen mode Exit fullscreen mode

Interactivity with OrbitControls 🕹️

What’s a 3D scene without interactivity? With OrbitControls, you can let users rotate, pan, and zoom in your 3D world.



const controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.update(); // Make sure the controls stay in sync with the camera



Enter fullscreen mode Exit fullscreen mode

Textures and Models: Bringing Realism to Life 🎨

loading 3D models and textures is key to building immersive experiences. Here’s how to load a 3D model of, say, a floating astronaut (because why not? 🤩):

Using the GLTFLoader:



const loader = new THREE.GLTFLoader();
loader.load('/path-to-your-model/astronaut.glb', function (gltf) {
  scene.add(gltf.scene); // Add the astronaut to the scene
});



Enter fullscreen mode Exit fullscreen mode

Real-World Example: Floating Astronaut in Space 🌌🧑‍🚀

Let’s bring everything together with a complete example — a floating astronaut in space! This example demonstrates everything we’ve covered so far: 3D models, textures, lights, animations, and interactivity.

Astronaut Floating

Key Aspects of the Code:

Astronaut Model:

The astronaut model (astronaut.glb) is loaded using useGLTF().
The model uses several textures (color, roughness, metalness, normal, and ambient occlusion).

Textures:

  1. Color Texture: Adds base color to the astronaut model.
  2. Roughness Texture: Determines how rough or smooth the surface of the astronaut is.
  3. Metalness Texture: Controls how metallic the material looks.
  4. Normal Texture: Adds surface detail to make the astronaut’s surface look more realistic.
  5. Ambient Occlusion (AO): Adds shadows in crevices to give the astronaut model more depth.

Lighting:

  1. Ambient Light: Adds overall brightness to the scene.
  2. Directional Light: Illuminates the astronaut from one direction, simulating sunlight.
  3. Spot Light: Adds focused light on the astronaut to emphasize key areas.

Post-Processing:

Bloom: A bloom effect is used to create a subtle glow, enhancing the overall visual appeal.

Controls:

OrbitControls: Allows the user to interact with the scene by zooming and panning around the astronaut.

Final Code for Floating Astronaut:

The code you provided implements a 3D floating astronaut in space using Three.js, React Three Fiber, and various textures. Below is an explanation of the code along with some minor improvements:



import * as THREE from 'three';
import React, { useRef, useEffect } from 'react';
import { Canvas, useFrame, useLoader } from '@react-three/fiber';
import { OrbitControls, useGLTF } from '@react-three/drei';
import { TextureLoader, AnimationMixer, BackSide } from 'three';
import { EffectComposer, Bloom } from '@react-three/postprocessing';

const Astronaut = () => {
  const { scene, animations } = useGLTF('/astronaut.glb'); // Load the astronaut model
  const mixer = useRef<AnimationMixer | null>(null);

  useEffect(() => {
    scene.scale.set(0.3, 0.3, 0.3); // Scale down the astronaut
  }, [scene]);

  useFrame((state, delta) => {
    if (!mixer.current && animations.length) {
      mixer.current = new AnimationMixer(scene);
      mixer.current.clipAction(animations[0]).play();
    }
    if (mixer.current) mixer.current.update(delta);
  });

  return <primitive object={scene} />;
};

const SpaceBackground = () => {
  const texture = useLoader(TextureLoader, '/textures/space-background.jpg');
  return (
    <mesh>
      <sphereGeometry args={[100, 32, 32]} />
      <meshBasicMaterial map={texture} side={BackSide} />
    </mesh>
  );
};

const App = () => {
  return (
    <Canvas>
      <SpaceBackground />
      <ambientLight intensity={1.5} />
      <directionalLight position={[10, 10, 10]} intensity={2} />
      <Astronaut />
      <OrbitControls />
      <EffectComposer>
        <Bloom intensity={0.7} />
      </EffectComposer>
    </Canvas>
  );
};

export default App;


Enter fullscreen mode Exit fullscreen mode
  • Astronaut Model: The astronaut model is loaded using GLTFLoader, animated with AnimationMixer.
  • Space Background: A large textured sphere acts as the space backdrop.
  • Lighting: Ambient and directional lights make the astronaut stand out, while bloom adds a glowing effect.
  • Interactivity: Users can pan, zoom, and rotate using OrbitControls. Heres how the result looks like:

Astronaut Floating Video

Wrapping Up 🌟

With Three.js, creating stunning 3D experiences has never been easier. Whether you’re interested in building games, interactive websites, or visualizing data in 3D, the possibilities are endless. In 2024, the web is more immersive than ever, and with Three.js, you can be a part of this exciting future.

GitHub Repository 📂

You can find the full source code for the floating astronaut in space project on GitHub. Feel free to explore, clone, and modify it to suit your needs.

GitHub Repository: 3D Floating Astronaut Project

Assets and Image Links 🌌

Happy coding, future 3D creator! 🚀

Top comments (0)