Building 3D Graphics with Three.js: A Step-by-Step Guide

28 Oct 2024 09:11 PM

Three.js is a popular JavaScript library used for creating 3D graphics directly in the browser. In this project, we’ll build a 3D rotating cube with lighting and materials to understand how to use Three.js effectively.

Project Overview

What We’ll Build:

  • A 3D rotating cube
  • Basic camera, lighting, and rendering setup
  • Orbit controls for interactive rotation

Step 1: Set Up the Project Structure

Create the following files:

/3DCube  
│
├── index.html  
├── styles.css  
└── script.js  

Step 2: Add HTML (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>3D Rotating Cube - Three.js</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <h1>3D Rotating Cube</h1>
  <div id="scene-container"></div>

  <!-- Include Three.js from CDN -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r134/three.min.js"></script>
  <!-- OrbitControls for interactive camera -->
  <script src="https://cdn.jsdelivr.net/npm/three@0.134/examples/js/controls/OrbitControls.js"></script>
  <script src="script.js"></script>
</body>
</html>

Step 3: Style the Scene (styles.css)

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #1a1a1a;
  color: white;
  flex-direction: column;
}

h1 {
  margin-bottom: 10px;
}

#scene-container {
  width: 800px;
  height: 600px;
  border: 2px solid white;
}

Step 4: Add JavaScript Logic (script.js)

// Set up the scene, camera, and renderer
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
  75, 
  800 / 600, 
  0.1, 
  1000
);

const renderer = new THREE.WebGLRenderer();
renderer.setSize(800, 600);
document.getElementById('scene-container').appendChild(renderer.domElement);

// Add orbit controls for interactive camera rotation
const controls = new THREE.OrbitControls(camera, renderer.domElement);

// Create a box geometry and basic material
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshStandardMaterial({ color: 0x44aa88 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

// Add lighting to the scene
const light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(5, 5, 5).normalize();
scene.add(light);

// Position the camera
camera.position.z = 5;

// Animation loop to rotate the cube and render the scene
function animate() {
  requestAnimationFrame(animate);

  // Rotate the cube
  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;

  // Update orbit controls
  controls.update();

  // Render the scene
  renderer.render(scene, camera);
}

// Start the animation loop
animate();

Step 5: Run the Project

  1. Open the index.html file in your browser.
  2. You’ll see a 3D rotating cube that you can interact with by dragging with your mouse (thanks to the OrbitControls).

Explanation

  1. Scene, Camera, and Renderer Setup:

    • The scene is where all objects are placed.
    • The camera defines the view of the scene.
    • The renderer renders the scene using WebGL.
  2. Geometry and Materials:

    • We created a BoxGeometry (the cube).
    • MeshStandardMaterial gives it a realistic material appearance with lighting.
  3. Lighting:

    • We added DirectionalLight to illuminate the cube, giving it depth.
  4. Orbit Controls:

    • The OrbitControls allow the user to rotate the camera interactively with the mouse.
  5. Animation Loop:

    • We use requestAnimationFrame() to rotate the cube and render the scene continuously for smooth animations.

Possible Enhancements

  • Add more shapes: Try adding spheres, cones, or custom models.
  • Change materials: Use MeshLambertMaterial or MeshPhongMaterial for different effects.
  • Add textures: Apply images as textures on the cube’s faces.
  • Introduce a skybox: Create a background with a panoramic view.
  • Physics: Integrate a physics engine like Cannon.js for realistic movements.

Conclusion

This project demonstrates the basics of 3D graphics using Three.js. You’ve created a rotating cube, added lighting, and allowed interactive camera control. Three.js opens up endless possibilities—from simple 3D objects to complex scenes with realistic lighting and physics.

Let me know if you want to add more features or build other exciting 3D projects!

1
14