Welcome to the exciting world of 3D on the web! In this chapter, we'll embark on our journey by creating our very first Three.js scene. Think of this as our 'Hello, World!' moment in three dimensions. We'll be setting up the fundamental building blocks that make any Three.js experience possible: a scene, a camera, and a renderer.
Before we write any code, let's understand the core components of a Three.js scene. We need three main things:
graph TD;
A[Scene] --> B(Camera);
A --> C(Renderer);
B --> C;
C --> D[HTML Canvas];
- Scene: This is like your virtual stage. It's where you'll place all your 3D objects, lights, and other elements.
- Camera: This is your viewpoint into the 3D world. It determines what the user sees and from what angle.
- Renderer: This component takes everything you've defined in your scene and rendered by your camera, and then draws it onto an HTML
<canvas>element on your webpage.
Let's start by setting up our HTML file. We'll need a basic HTML structure and a <canvas> element where our 3D scene will be rendered.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Three.js Hello World</title>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; }
</style>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="script.js"></script>
</body>
</html>In this HTML, we've included the Three.js library from a CDN. This makes the Three.js functionality available to our JavaScript. We also have a <canvas> element with the ID myCanvas, and we're linking to a script.js file where our Three.js code will live.