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:
- WebXR and WebGL: Virtual reality (VR) and augmented reality (AR) on the web are growing, and Three.js is WebXR-ready.
- Cross-Browser Support: It works seamlessly across modern browsers, including mobile ones.
- Lightweight 3D Creation: No need to learn complex WebGL. Three.js makes 3D creation as easy as writing JavaScript.
- 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();
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
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
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
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
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();
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
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
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);
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 });
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
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
});
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.
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:
- Color Texture: Adds base color to the astronaut model.
- Roughness Texture: Determines how rough or smooth the surface of the astronaut is.
- Metalness Texture: Controls how metallic the material looks.
- Normal Texture: Adds surface detail to make the astronautโs surface look more realistic.
- Ambient Occlusion (AO): Adds shadows in crevices to give the astronaut model more depth.
Lighting:
- Ambient Light: Adds overall brightness to the scene.
- Directional Light: Illuminates the astronaut from one direction, simulating sunlight.
- 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;
- 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:
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 ๐
3D Astronaut Model: The astronaut model used in this project can be found on Sketchfab.
Animated Floating Astronaut in Space Suit (Sketchfab)Background Image: The background space image is provided by Alex Myers from Pixabay.
Image by Alex Myers from Pixabay.
Happy coding, future 3D creator! ๐
Top comments (0)