Build a 3D Environment with Three.js
Three.js is a powerful JavaScript library that simplifies the creation and display of 3D graphics in a web browser. It abstracts away the complexities of WebGL, making it easier for developers to create stunning 3D experiences. This article will guide you through the process of building a basic 3D environment using Three.js, covering essential concepts and techniques.
What is Three.js?
Three.js is a cross-browser JavaScript library and API used to create and display animated 3D computer graphics in a web browser using WebGL. It allows developers to create rich, interactive 3D experiences without having to write complex WebGL code directly. Key features of Three.js include:
- Scene Graph: A hierarchical structure for organizing and managing 3D objects.
- Renderers: Different renderers for WebGL, Canvas, CSS3D, and SVG.
- Materials: A wide range of materials for defining the appearance of objects (e.g., color, texture, reflectivity).
- Geometries: Pre-built geometries (e.g., cubes, spheres, planes) and tools for creating custom geometries.
- Lights: Various types of lights for illuminating the scene (e.g., ambient, directional, point).
- Cameras: Different camera types for controlling the viewpoint (e.g., perspective, orthographic).
- Animations: Tools for creating animations and interactive experiences.
Prerequisites
- Basic knowledge of HTML, CSS, and JavaScript
- A code editor (e.g., VS Code)
- A web browser
Setting Up Your Project
-
Create a Project Directory:
Create a new directory for your project, e.g.,
threejs-environment. -
Create Essential Files:
Inside the project directory, create the following files:
index.html: The main HTML file.style.css: The CSS file for styling.script.js: The JavaScript file for Three.js code.
-
Include Three.js:
You can include Three.js in your project in a few ways:
-
CDN: Add the following line to the
<head>of yourindex.htmlfile:html<script src="https://cdn.jsdelivr.net/npm/three@0.155.0/build/three.min.js"></script> -
NPM: If you're using a package manager like NPM, you can install Three.js:
bashnpm install threeThen, import it in your
script.jsfile:javascriptimport * as THREE from 'three';
-
Creating the Scene
-
HTML Structure (
index.html):html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>3D Environment with Three.js</title> <link rel="stylesheet" href="style.css"> </head> <body> <canvas id="bg"></canvas> <script type="module" src="script.js"></script> </body> </html> -
CSS Styling (
style.css):cssbody { margin: 0; overflow: hidden; /* Hide scrollbars */ } canvas { width: 100%; height: 100%; display: block; } -
JavaScript (
script.js):javascriptimport * as THREE from 'three'; // 1. Create a Scene const scene = new THREE.Scene(); // 2. Create a Camera const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.z = 5; // 3. Create a Renderer const renderer = new THREE.WebGLRenderer({ canvas: document.querySelector('#bg'), }); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(window.innerWidth, window.innerHeight); // 4. Add an Object (Example: A Cube) const geometry = new THREE.BoxGeometry(1, 1, 1); const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); const cube = new THREE.Mesh(geometry, material); scene.add(cube); // 5. Animation Loop function animate() { requestAnimationFrame(animate); cube.rotation.x += 0.01; cube.rotation.y += 0.01; renderer.render(scene, camera); } animate();- Scene: The container for all objects, lights, and cameras.
- Camera: Defines the viewpoint from which the scene is rendered.
PerspectiveCameramimics human vision. - Renderer: Renders the scene to the canvas using WebGL.
- Geometry: The shape of the object (e.g., cube, sphere).
- Material: The surface properties of the object (e.g., color, texture).
- Mesh: The combination of geometry and material.
- Animation Loop: A function that is called repeatedly to update the scene and render it.
Adding More Objects
You can add more objects to your scene by creating different geometries and materials. Here's an example of adding a sphere:
const sphereGeometry = new THREE.SphereGeometry(0.75, 32, 32);
const sphereMaterial = new THREE.MeshBasicMaterial({ color: 0xff00ff });
const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
sphere.position.x = -2;
scene.add(sphere);
Adding Lights
Basic material doesn't react to light. Let's use MeshStandardMaterial and add some lights.
const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
const sphereMaterial = new THREE.MeshStandardMaterial({ color: 0xff00ff });
const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
// Add ambient light
const ambientLight = new THREE.AmbientLight(0x404040); // Soft white light
scene.add(ambientLight);
// Add directional light
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(5, 3, 5); // x, y, z
scene.add(directionalLight);
Creating a Background
To make the environment more immersive, you can add a background. This can be a simple color or a more complex texture.
scene.background = new THREE.Color(0xADD8E6); // Light blue
Adding Orbit Controls
Orbit controls allow you to rotate around the scene using your mouse. To add orbit controls, you'll need to include the OrbitControls.js file from the Three.js examples directory.
-
HTML Structure (
index.html):html<script src="https://cdn.jsdelivr.net/npm/three@0.155.0/examples/jsm/controls/OrbitControls.js"></script> -
JavaScript (
script.js):javascriptimport { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'; const controls = new OrbitControls(camera, renderer.domElement); function animate() { requestAnimationFrame(animate); cube.rotation.x += 0.01; cube.rotation.y += 0.01; controls.update(); // Update the controls each frame renderer.render(scene, camera); }
Conclusion
This article provides a basic introduction to building a 3D environment with Three.js. You can expand upon this foundation by adding more complex objects, textures, lighting effects, and interactions. Experiment with different Three.js features to create your own unique and immersive 3D worlds.