Now that we've explored the core components of a Three.js application – the Scene, Camera, and Renderer – it's time to bring them together and create our very first, albeit simple, 3D web experience. This section will guide you step-by-step through setting up a basic Three.js project.
We'll start by creating an HTML file that will serve as the container for our 3D canvas. This is where our Three.js magic will happen. We'll also need a JavaScript file where we'll write our Three.js code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My First Three.js Scene</title>
<style>
body { margin: 0; }
canvas { display: block; }
</style>
</head>
<body>
<script type="module" src="main.js"></script>
</body>
</html>In the HTML above, we've set up a basic page. The key elements are the <title> for our browser tab and the <style> block which ensures the canvas takes up the full screen by removing default margins and setting the canvas to display as a block. Most importantly, we include our JavaScript file main.js using <script type="module" src="main.js"></script>. Using type="module" allows us to use modern JavaScript features like import and export which are essential for larger Three.js projects.
Now, let's create our main.js file and begin constructing our 3D scene.
// Import necessary Three.js components
import * as THREE from 'three';
// 1. Create a Scene
const scene = new THREE.Scene();
// 2. Create a Camera
// Field of View (FOV): 75 degrees
// Aspect Ratio: window.innerWidth / window.innerHeight
// Near Clipping Plane: 0.1 (objects closer than this won't be rendered)
// Far Clipping Plane: 1000 (objects further than this won't be rendered)
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
// Position the camera back so we can see something
camera.position.z = 5;
// 3. Create a Renderer
const renderer = new THREE.WebGLRenderer();
// Set the size of the renderer to fill the window
renderer.setSize(window.innerWidth, window.innerHeight);
// Append the renderer's DOM element (the canvas) to our HTML body
document.body.appendChild(renderer.domElement);
// --- We'll add objects and animation next! ---