3D Development Documentation

Comprehensive guides and references for building immersive 3D web experiences

Getting Started with 3D Web Development

Welcome to the world of 3D web development! This guide will help you set up your environment and create your first 3D scene.

Prerequisites

  • Basic knowledge of HTML, CSS, and JavaScript
  • Modern web browser (Chrome, Firefox, Edge, or Safari)
  • Code editor (VS Code, Sublime Text, etc.)
  • Node.js installed (for package management)

Setting Up Your Project

Start by creating a new project directory and initializing it with npm:

// Create project directory mkdir my-3d-project cd my-3d-project // Initialize npm project npm init -y // Install Three.js npm install three // Optional: Install build tools npm install --save-dev vite @vitejs/plugin-basic-ssl

Create an index.html file and a main.js file in your project directory.

Your First 3D Scene

Here's a simple Three.js scene to get you started:

import * as THREE from 'three'; // Create scene const scene = new THREE.Scene(); // Create 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 ); // Create renderer const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); // Create 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); // Position camera camera.position.z = 5; // Animation loop function animate() { requestAnimationFrame(animate); // Rotate cube cube.rotation.x += 0.01; cube.rotation.y += 0.01; // Render scene renderer.render(scene, camera); } // Start animation animate();

Pro Tip

Use Vite or another modern build tool to leverage ES modules and hot reloading for a better development experience.

Three.js Fundamentals

Three.js is a powerful JavaScript library that makes WebGL easier to work with. Let's explore its core concepts.

Core Components

Every Three.js application consists of these fundamental components:

Scene

The container for all your 3D objects, lights, and cameras. Think of it as a stage where your 3D world exists.

Camera

Defines what part of the scene is visible. PerspectiveCamera mimics how human vision works.

Renderer

Draws your scene to the screen using WebGL. Handles the actual rendering process.

Lights

Illuminate your scene. Different types (Ambient, Directional, Point, etc.) create different lighting effects.

Creating Objects

Objects in Three.js consist of a geometry (shape) and a material (appearance). Here's how to create them:

// Basic geometries const boxGeometry = new THREE.BoxGeometry(1, 1, 1); const sphereGeometry = new THREE.SphereGeometry(0.5, 32, 32); const cylinderGeometry = new THREE.CylinderGeometry(0.5, 0.5, 1, 32); // Basic materials const basicMaterial = new THREE.MeshBasicMaterial({ color: 0x00ff00, wireframe: false }); const standardMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000, roughness: 0.5, metalness: 0.5 }); // Combining geometry and material into a mesh const box = new THREE.Mesh(boxGeometry, basicMaterial); const sphere = new THREE.Mesh(sphereGeometry, standardMaterial); // Add to scene scene.add(box); scene.add(sphere); // Position objects box.position.set(-2, 0, 0); sphere.position.set(2, 0, 0);

Animation Loop

Three.js uses a render loop to animate your scene. Here's an advanced example with controls:

import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'; // Clock for consistent animation speed const clock = new THREE.Clock(); // Add orbit controls const controls = new OrbitControls(camera, renderer.domElement); controls.enableDamping = true; controls.dampingFactor = 0.05; // Animation loop function animate() { requestAnimationFrame(animate); // Get delta time for consistent speed const delta = clock.getDelta(); // Update controls controls.update(); // Rotate objects box.rotation.x += 0.5 * delta; sphere.rotation.y += 0.5 * delta; // Render scene renderer.render(scene, camera); } animate();

Shaders & GLSL Programming

Shaders give you low-level control over the rendering pipeline, enabling stunning visual effects.

Shader Basics

Shaders are programs that run on the GPU. There are two main types:

Vertex Shader

Processes each vertex's position. Can modify geometry, apply deformations, etc.

Fragment Shader

Determines the color of each pixel. Used for materials, lighting, post-processing.

Custom Shader Material

Create a material with custom vertex and fragment shaders:

// Vertex shader code const vertexShader = ` varying vec2 vUv; void main() { vUv = uv; // Add a simple wave deformation vec3 newPosition = position; newPosition.y += sin(position.x * 5.0) * 0.2; gl_Position = projectionMatrix * modelViewMatrix * vec4(newPosition, 1.0); } `; // Fragment shader code const fragmentShader = ` varying vec2 vUv; uniform float time; void main() { // Create a gradient based on UV coordinates vec3 color = mix( vec3(0.2, 0.3, 0.8), vec3(0.8, 0.2, 0.3), vUv.y ); // Add pulsing effect with time float pulse = sin(time) * 0.5 + 0.5; color *= pulse; gl_FragColor = vec4(color, 1.0); } `; // Create shader material const shaderMaterial = new THREE.ShaderMaterial({ vertexShader: vertexShader, fragmentShader: fragmentShader, uniforms: { time: { value: 0 } } }); // Create mesh with shader material const planeGeometry = new THREE.PlaneGeometry(5, 5, 32, 32); const plane = new THREE.Mesh(planeGeometry, shaderMaterial); scene.add(plane); // In animation loop, update time uniform function animate() { requestAnimationFrame(animate); // Update shader time shaderMaterial.uniforms.time.value = performance.now() / 1000; renderer.render(scene, camera); }

Shader Examples

Here are some common shader effects you can implement:

Toon Shading

Creates a cartoon-like effect with discrete color bands.

// In fragment shader: float intensity = dot(normal, lightDirection); intensity = floor(intensity * 3.0) / 3.0; // Quantize vec3 color = baseColor * intensity;

Water Ripple

Simulates water surface with dynamic ripples.

// In vertex shader: float distance = length(position.xz - rippleCenter); float wave = sin(distance * 10.0 - time * 3.0) * 0.1; newPosition.y += wave * exp(-distance * 0.5);

Performance Optimization

Creating smooth 3D experiences requires careful attention to performance. Here are key optimization techniques.

Instanced Meshes

For rendering many similar objects efficiently, use instanced meshes:

const COUNT = 1000; const geometry = new THREE.BoxGeometry(0.5, 0.5, 0.5); const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 }); const mesh = new THREE.InstancedMesh(geometry, material, COUNT); const matrix = new THREE.Matrix4(); const positions = []; for (let i = 0; i < COUNT; i++) { const x = Math.random() * 20 - 10; const y = Math.random() * 20 - 10; const z = Math.random() * 20 - 10; matrix.makeRotationFromEuler( new THREE.Euler( Math.random() * Math.PI, Math.random() * Math.PI, Math.random() * Math.PI ) ); matrix.setPosition(x, y, z); mesh.setMatrixAt(i, matrix); positions.push({ x, y, z }); } scene.add(mesh); // In animation loop: for (let i = 0; i < COUNT; i++) { const position = positions[i]; matrix.makeRotationFromEuler( new THREE.Euler( time + i * 0.1, time * 0.5 + i * 0.1, time * 0.3 + i * 0.1 ) ); matrix.setPosition( position.x, position.y + Math.sin(time + i) * 0.5, position.z ); mesh.setMatrixAt(i, matrix); } mesh.instanceMatrix.needsUpdate = true;

Level of Detail (LOD)

Reduce polygon count for distant objects:

const lod = new THREE.LOD(); // High detail (up close) const highDetailGeo = new THREE.SphereGeometry(1, 32, 32); const highDetailMat = new THREE.MeshStandardMaterial({ color: 0xff0000 }); const highDetailMesh = new THREE.Mesh(highDetailGeo, highDetailMat); lod.addLevel(highDetailMesh, 0); // Medium detail const medDetailGeo = new THREE.SphereGeometry(1, 16, 16); const medDetailMat = new THREE.MeshStandardMaterial({ color: 0x00ff00 }); const medDetailMesh = new THREE.Mesh(medDetailGeo, medDetailMat); lod.addLevel(medDetailMesh, 20); // Low detail (far away) const lowDetailGeo = new THREE.SphereGeometry(1, 8, 8); const lowDetailMat = new THREE.MeshStandardMaterial({ color: 0x0000ff }); const lowDetailMesh = new THREE.Mesh(lowDetailGeo, lowDetailMat); lod.addLevel(lowDetailMesh, 50); scene.add(lod);

Performance Tips

  • Memory Management

    Dispose of unused geometries, materials, and textures to free up memory: geometry.dispose(); material.dispose(); texture.dispose();

  • Render Optimization

    Use frustumCulled to avoid rendering objects outside the camera view: mesh.frustumCulled = true;

  • Lighting Efficiency

    Limit the number of lights in your scene. Each additional light increases rendering cost exponentially.

Need more help? Contact our support team or join our community forum.

Last updated: June 2023 | Documentation version 3.2.1