Three.js & WebGL — Complete Notes
📁 For all code examples and projects, visit the GitHub Repository:
Advance-Frontend by kartik-hub-enjay
🌐 What is WebGL?
WebGL (Web Graphics Library) is a JavaScript API that allows you to render 3D and 2D graphics directly in a web browser without needing any plugins.
- WebGL lets you use your GPU (graphics card) to draw graphics on a webpage using the
<canvas>element.
🔷 What is Three.js?
Three.js is a JavaScript library that makes it easy to create 3D graphics in the browser using WebGL.
Three.js = an easy layer on top of WebGL
Instead of writing complex WebGL code, you use simple JavaScript to create 3D scenes.
When working with Three.js, you always deal with these 3 things:
| Component | Description |
|---|---|
| Scene | The world — everything exists here |
| Camera | What the user sees |
| Renderer | Displays the scene on screen |
Canvas
A Canvas is an HTML element used to draw graphics (2D or 3D) directly on a web page using JavaScript.
Scene
In 3D graphics (especially in Three.js), a Scene is the main container that holds everything you want to display.
Scene = the virtual world where all objects exist
Think of it like a movie set:
| Movie Analogy | Three.js Equivalent |
|---|---|
| Actors | Objects (cube, sphere, models) |
| Lights | Lighting |
| Camera | Viewpoint |
| Stage | The Scene itself |
What Does a Scene Contain?
A scene can include:
- 3D objects (meshes, models)
- Lights (for brightness and shadows)
- Cameras (to view the scene)
- Animations
The Core Trio
Scene → What exists | Camera → What you see | Renderer → Displays it
The renderer shows the scene through the camera.
Camera
In 3D graphics (like in Three.js), a Camera defines what part of the scene is visible on the screen.
Camera = the viewer's eyes in a 3D world
Think of shooting a movie:
- Scene → entire set
- Camera → what angle you see
- Screen → final output
Change camera → you see a different view
Types of Cameras
1. Perspective Camera (Most Used)
- Works like human eyes
- Objects far away look smaller
- Used in games, websites, real-world views
2. 📐 Orthographic Camera
- No perspective effect
- Objects stay same size
- Used in 2D games, UI, CAD apps
Camera Properties
| Property | Description |
|---|---|
| Position | Where the camera is |
| Rotation | Where it is looking |
| Field of View (FOV) | How wide the view is |
Rotation
Rotation = turning an object around an axis
Objects rotate around 3 axes:
| Axis | Direction | Analogy |
|---|---|---|
| X-axis | Up / Down tilt | 😮 Nodding head |
| Y-axis | Left / Right spin | 🙅 Shaking head |
| Z-axis | Clockwise / Anticlockwise | 🎡 Rotating a wheel |
Scaling
Scaling = changing the size of an object
Scaling works on axes:
| Axis | Controls |
|---|---|
| X | Width |
| Y | Height |
| Z | Depth |
Mesh
In 3D graphics (like in Three.js), a Mesh is the actual visible 3D object you see on the screen.
Mesh = Geometry + Material
A mesh is made of 2 parts:
1. Geometry
- Defines the shape
- Example: cube, sphere, plane
2. Material
- Defines the appearance
- Color, texture, light effect
Renderer
In the world of Three.js, the Renderer is essentially the engine's "artist." It takes all the mathematical data you've created — your 3D objects, the lights, and the camera's perspective — and does the hard work of drawing those pixels onto your 2D screen.
Think of it as the final step in the pipeline: you provide the scene (the stage) and the camera (the eyes), and the renderer produces the image.
Most Three.js projects use the WebGLRenderer. This specifically utilizes the browser's WebGL API to harness the power of the user's GPU (Graphics Card). This is why 3D on the web can run at high frame rates (like 60 FPS) even with complex geometry.
requestAnimationFrame
In Three.js, requestAnimationFrame (RAF) is the heartbeat of your application. While it is technically a native Web API provided by the browser, it is essential for Three.js because it creates the Render Loop that makes motion possible.
- Without it → your 3D scene would be a static snapshot
- With it → you can move objects, update physics, and see changes in real-time
Why use it instead of setInterval?
| Feature | requestAnimationFrame |
|---|---|
| Sync with Refresh Rate | Matches monitor frame rate (60Hz or 144Hz) — buttery-smooth motion |
| Battery & Performance | Pauses automatically when tab is hidden |
| Frame Efficiency | Executes at the right moment before repaint, reducing jank |
Handling Different Frame Rates
One common "gotcha" with requestAnimationFrame is that it runs as fast as the monitor allows. If a user has a 144Hz monitor, your cube will spin much faster than for a user on a 60Hz monitor.
To fix this, developers use a Clock to ensure animations are "frame-rate independent."
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
// Get the time elapsed since the last frame
const delta = clock.getDelta();
// Move 1 unit per second, regardless of FPS
mesh.position.x += 1 * delta;
renderer.render(scene, camera);
}
Orbit Controls
In Three.js, OrbitControls is a utility that lets the user interactively move the camera around a scene using the mouse or touch.
OrbitControls = allows you to rotate, zoom, and pan the camera around an object
With OrbitControls, users can:
| Action | How |
|---|---|
| Rotate | Drag mouse to spin around object |
| Zoom | Scroll to zoom in/out |
| Pan | Move left/right/up/down |
Important Note: OrbitControls does NOT move objects — it moves the camera around the scene.
Geometry
In 3D graphics (like in Three.js), Geometry defines the shape or structure of an object.
Geometry is made up of:
| Component | Description |
|---|---|
| Vertices | Points in space |
| Edges | Lines connecting points |
| Faces | Surfaces (triangles) |
Together, they form a 3D shape.
Geometry only defines shape — it is not visible until combined with a material.
Materials
In 3D graphics (like in Three.js), Materials define how an object looks on the surface.
Material = the appearance (color, texture, light behavior) of an object
Types of Materials
| Type | Description |
|---|---|
| Basic Material | No lighting effect — always looks the same |
| Standard Material | Realistic lighting — supports shadows |
| Phong Material | Shiny surface — reflects light |
What Materials Control
- Color
- Texture (images)
- Shininess
- Light reflection
- Transparency
Textures
In 3D graphics (like in Three.js), Textures are images applied to the surface of an object to make it look more realistic or detailed.
Types of Textures
| Type | Purpose |
|---|---|
| Color Map | Basic image |
| Normal Map | Fake surface details |
| Roughness Map | Smooth/rough surface |
| Metalness Map | Metallic look |
lil-GUI
lil-gui is a small JavaScript library used to create a control panel (UI sliders, buttons, toggles) to interact with your code in real time.
lil-gui = a UI tool to control variables live (while your app is running)
When working with 3D (like in Three.js), you often want to:
- Change colors
- Adjust rotation
- Modify light intensity
- Tune animations
Instead of editing code again and again, lil-gui lets you control everything with sliders.
Lights
In Three.js, Lights are what transform a flat, 2D-looking shape into a 3D object with depth, shadows, and contours. Without light, your scene will either be pitch black or — if you are using a MeshBasicMaterial — flat and devoid of shading.
To use lights, you need two things: a Light source and a Material that reacts to light (like
MeshStandardMaterialorMeshPhongMaterial).
Common Light Types
There are several types of lights in Three.js, each serving a specific purpose in a 3D environment.
See full light type reference: Three.js Lighting Docs
Lighting Theory: The "Three-Point" Setup
For professional-looking scenes, developers often use a "Three-Point Lighting" setup:
| Light | Role |
|---|---|
| Key Light | Main light source |
| Fill Light | Softens shadows |
| Back Light | Creates a rim effect, separates object from background |
Working with Shadows
Shadows are computationally "expensive," so they are disabled by default. To see shadows, follow this three-step checklist:
// Step 1: Enable the Renderer
renderer.shadowMap.enabled = true;
// Step 2: Enable the Light
light.castShadow = true;
// Step 3: Enable the Objects
mesh.castShadow = true; // Object casts shadow
floor.receiveShadow = true; // Floor receives shadow
Helpers: "Seeing" the Light
Since lights are invisible, it can be frustrating to guess where they are pointing. Three.js provides Helpers to visualize them.
📁 Code Reference
All code examples, projects, and implementations are available on GitHub:
Top comments (0)