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!
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:
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!
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();
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
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
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
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
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 ! ?
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
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!
3D graphics are nothing without light. The more realistic the lighting, the more impressive your 3D world becomes. Let’s explore:
Without light, even the best 3D models will look flat and lifeless. In Three.js, there are several types of lights:
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);
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 });
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
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? ?):
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 });
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.
The astronaut model (astronaut.glb) is loaded using useGLTF().
The model uses several textures (color, roughness, metalness, normal, and ambient occlusion).
Bloom: A bloom effect is used to create a subtle glow, enhancing the overall visual appeal.
OrbitControls: Allows the user to interact with the scene by zooming and panning around the 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(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 ; }; const SpaceBackground = () => { const texture = useLoader(TextureLoader, '/textures/space-background.jpg'); return ( ); }; const App = () => { return ( ); }; export default App;
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.
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
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! ?
Отказ от ответственности: Все предоставленные ресурсы частично взяты из Интернета. В случае нарушения ваших авторских прав или других прав и интересов, пожалуйста, объясните подробные причины и предоставьте доказательства авторских прав или прав и интересов, а затем отправьте их по электронной почте: [email protected]. Мы сделаем это за вас как можно скорее.
Copyright© 2022 湘ICP备2022001581号-3