Creating a Basic Scene

Back to Modules

Your First Steps into the 3D World with Three.js

Creating a 3D scene in Three.js involves setting up a renderer, a scene, and a camera. These are the absolute minimum requirements to display anything in 3D on your web page.

The Renderer

The renderer is responsible for taking your 3D scene and displaying it on a 2D canvas. The most common renderer is `WebGLRenderer`, which uses the WebGL API for hardware-accelerated 3D graphics.

Code Example: Initializing the Renderer

import * as THREE from 'three';

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

The Scene

The scene is where you place all your 3D objects, lights, and cameras. Think of it as a container or a stage for your 3D world.

Code Example: Creating a Scene

const scene = new THREE.Scene();

The Camera

The camera defines what the user sees in your 3D scene. There are different types of cameras, but `PerspectiveCamera` is the most common for simulating human vision.

Code Example: Setting up a Camera

const camera = new THREE.PerspectiveCamera(
  75, // Field of view
  window.innerWidth / window.innerHeight, // Aspect ratio
  0.1, // Near clipping plane
  1000 // Far clipping plane
);
camera.position.z = 5; // Move camera back to see objects

Putting It All Together: The Render Loop

To make your scene interactive and dynamic, you need a render loop. This function is called repeatedly (typically 60 times per second) to update the scene and redraw the frame.

Code Example: The Basic Render Loop

function animate() {
  requestAnimationFrame(animate);
  // Update objects here (e.g., cube.rotation.x += 0.01;)
  renderer.render(scene, camera);
}
animate();

Case Study: A Simple Product Showcase

Imagine you want to display a 3D model of a product on a webpage. By setting up a basic Three.js scene, you can load your product model, add some lighting to make it visible, and position a camera to give the user a good view. The render loop would then allow for simple animations or user interactions like rotating the product.