Three.js is a powerful JavaScript library for creating 3D graphics in the browser. It leverages WebGL to render high-performance 3D scenes, making it a popular choice for developers building interactive 3D applications, games, and visualizations.
This tutorial will guide you through the basics of Three.js, including setting up a project, creating 3D objects, and animating them. By the end of this tutorial, you’ll have a solid foundation to start building your own 3D applications.
Prerequisites
Before diving into this tutorial, make sure you have the following:
- Basic Knowledge of HTML, CSS, and JavaScript: While this tutorial focuses on Three.js, a foundational understanding of web technologies is essential.
- Understanding of 3D Concepts: Familiarity with concepts like vertices, faces, and transformations (rotation, scaling, translation) will help you grasp the material more quickly.
Setting Up Your Project
Let’s start by setting up a basic HTML structure and including the Three.js library.
Step 1: Create an HTML File
Create a new HTML file (index.html
) and add the following code:
<!DOCTYPE html>
<html>
<head>
<title>Three.js Tutorial</title>
<style>
body { margin: 0; }
canvas { display: block; }
</style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="app.js"></script>
</body>
</html>
Step 2: Initialize the Scene, Camera, and Renderer
Create a new JavaScript file (app.js
) and add the following code:
// Set up 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);
document.body.appendChild(renderer.renderingContext.canvas);
// Set camera position
camera.position.z = 5;
// Render the scene
renderer.render(scene, camera);
This code sets up a basic scene with a camera and renderer. The camera is positioned 5 units away from the origin, and the renderer is added to the body of the HTML document.
Understanding Core Concepts
Before we dive into creating 3D objects, let’s understand some core concepts in Three.js.
Scene
The Scene
object is the container for all the objects in your 3D world. Think of it as the stage where all your 3D objects will reside.
Camera
The Camera
defines how your 3D scene will be viewed. There are different types of cameras, but the most commonly used one is the PerspectiveCamera
, which mimics how the human eye sees the world.
Renderer
The Renderer
is responsible for rendering your 3D scene onto a 2D surface (like a canvas). Three.js provides different renderers, but the most commonly used one is the WebGLRenderer
.
Creating 3D Objects
Now that we have a basic setup, let’s create some 3D objects.
Step 1: Creating a Cube
Add the following code to app.js
after setting up the scene, camera, and renderer:
// Create a cube
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
// Add the cube to the scene
scene.add(cube);
This code creates a green cube and adds it to the scene. The BoxGeometry
defines the shape of the cube, the MeshBasicMaterial
defines its appearance, and the Mesh
combines the geometry and material to create the final object.
Step 2: Creating a Sphere
Add the following code to create a sphere:
// Create a sphere
const sphereGeometry = new THREE.SphereGeometry(1, 32, 32);
const sphereMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
// Add the sphere to the scene
scene.add(sphere);
// Position the sphere
sphere.position.x = 2;
This code creates a red sphere and positions it 2 units to the right of the cube.
Adding Lighting
Lighting is essential to make your 3D objects look realistic. Let’s add some lights to our scene.
Step 1: Adding Ambient Light
Add the following code to app.js
:
// Add ambient light
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
This code adds an ambient light to the scene, which provides overall illumination.
Step 2: Adding Point Light
Add the following code to add a point light:
// Add point light
const pointLight = new THREE.PointLight(0xffffff, 1);
pointLight.position.set(5, 5, 5);
scene.add(pointLight);
This code adds a point light at position (5, 5, 5), which creates a more dynamic lighting effect.
Animating Objects
Now that we have some objects in our scene, let’s make them move.
Step 1: Creating an Animation Function
Add the following code to app.js
:
// Animation function
function animate() {
requestAnimationFrame(animate);
// Rotate the cube
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
// Rotate the sphere
sphere.rotation.x += 0.01;
sphere.rotation.y += 0.01;
renderer.render(scene, camera);
}
// Start the animation
animate();
This code uses requestAnimationFrame
to create a smooth animation loop. The cube and sphere are rotated by incrementing their rotation values each frame.
Handling User Interaction
Three.js allows you to handle user interaction, such as mouse and keyboard events. Let’s add some interactivity to our scene.
Step 1: Adding Mouse Interaction
Add the following code to app.js
:
// Add event listeners
window.addEventListener('resize', onWindowResize);
window.addEventListener('mousemove', onMouseMove);
// Handle window resize
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
// Handle mouse move
function onMouseMove(event) {
cube.rotation.x = event.clientY * 0.001;
cube.rotation.y = event.clientX * 0.001;
}
This code adds event listeners for window resize and mouse move events. The onWindowResize
function adjusts the camera aspect ratio and renderer size, while the onMouseMove
function rotates the cube based on the mouse position.
Best Practices
Here are some best practices to keep in mind when working with Three.js:
- Optimize Performance: Complex scenes can be resource-intensive. Use techniques like level of detail (LOD) and occlusion culling to optimize performance.
- Use Efficient Materials: Avoid using overly complex materials unless necessary. Simple materials like
MeshBasicMaterial
can be more efficient. - Handle Resizing: Always handle window resizing to ensure your scene looks good on different screen sizes.
- Debugging: Use the browser’s developer tools to debug your code. Three.js provides some useful utilities for debugging, such as the
AxesHelper
.
Real-World Example
Let’s create a more complex example that combines everything we’ve learned so far.
Step 1: Creating a Solar System
Add the following code to app.js
:
// Create the sun
const sunGeometry = new THREE.SphereGeometry(1, 32, 32);
const sunMaterial = new THREE.MeshBasicMaterial({ color: 0xffff00 });
const sun = new THREE.Mesh(sunGeometry, sunMaterial);
scene.add(sun);
// Create planets
const planetGeometry = new THREE.SphereGeometry(0.2, 32, 32);
const planetMaterial = new THREE.MeshBasicMaterial({ color: 0x0000ff });
const planet1 = new THREE.Mesh(planetGeometry, planetMaterial);
planet1.position.x = 2;
scene.add(planet1);
const planet2 = new THREE.Mesh(planetGeometry, planetMaterial);
planet2.position.x = -2;
scene.add(planet2);
// Animate planets
function animate() {
requestAnimationFrame(animate);
planet1.rotation.y += 0.01;
planet2.rotation.y += 0.01;
planet1.position.x = Math.sin(Date.now() * 0.001) * 2;
planet2.position.x = Math.cos(Date.now() * 0.001) * 2;
renderer.render(scene, camera);
}
// Start the animation
animate();
This code creates a simple solar system with a sun and two planets. The planets orbit around the sun and rotate on their axes.
Frequently Asked Questions
Q: Why is my 3D object not showing up?
A: There are several reasons why your object might not be showing up:
1. The object is outside the camera’s view frustum. Check the camera’s position and the object’s position.
2. The object’s material is not visible. Check the material’s color and properties.
3. The object is not added to the scene. Make sure you call scene.add(object)
.
Q: How do I handle user input?
A: You can handle user input by adding event listeners to the window or the renderer’s canvas. Three.js provides some utilities for handling user input, such as the PointerLockControls
and OrbitControls
.
Q: How do I optimize performance?
A: To optimize performance, you can:
1. Use efficient materials and geometries.
2. Use level of detail (LOD) techniques.
3. Use occlusion culling to avoid rendering objects that are not visible.
4. Minimize the number of draw calls by using batched rendering.
Q: How do I create custom geometries?
A: You can create custom geometries by defining your own vertices and faces. Three.js provides the BufferGeometry
class for creating custom geometries. You can also use external tools like Blender to create 3D models and export them as JSON or other formats supported by Three.js.
Conclusion
Three.js is a powerful library for creating 3D graphics in the browser. With its extensive API and active community, it’s a great choice for developers looking to build interactive 3D applications. By following this tutorial, you should now have a solid foundation to start exploring the possibilities of Three.js.
Tags
[“Three.js”, “JavaScript”, “3D Graphics”, “WebGL”, “Interactive Applications”, “Animation”, “Lighting”, “Materials”, “User Interaction”, “Performance Optimization”]