All articles

3D Graphics

Introduction to Three.js for Web Developers

Get started with 3D graphics on the web using Three.js. Create stunning visual experiences for your users.

Aditya Patel1 min read8 views

What is Three.js?

Three.js is a powerful JavaScript library that makes creating 3D graphics in the browser accessible and fun. It abstracts the complexities of WebGL.

Basic Setup

Install Three.js in your project:

npm install three

Creating Your First Scene

Every Three.js project needs three main components:

  • Scene - The container for all objects
  • Camera - The viewpoint
  • Renderer - Draws the scene
import * as THREE from 'three';

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();

renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

Adding Objects

Create a simple cube:

const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

Animation

Bring your scene to life with animation:

function animate() {
  requestAnimationFrame(animate);
  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;
  renderer.render(scene, camera);
}
animate();

Next Steps

  • Explore lighting and shadows
  • Load 3D models
  • Add interactivity with raycasting
  • Optimize performance

Tags

  • Three.js
  • WebGL
  • 3D
  • JavaScript