Open In App

Three.js - JavaScript 3D Library

Last Updated : 21 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Three.js is a powerful and popular JavaScript library used for creating and rendering 3D graphics in web applications. It uses WebGL API behind the scenes and allows you to use your GPU (Graphics Processing Unit) to render the Graphics and 3D objects on a canvas in the web browser.

It provides an intuitive API to handle complex tasks like lighting, camera positioning, materials, and physics simulations. Instead of manually managing WebGL shaders and buffers, you can use Three.js to create realistic 3D environments, animated objects, and interactive graphics with minimal effort. Its versatility makes it ideal for applications in gaming, data visualization, augmented reality, and more.

How Three.js Works

Three.js follows a basic structure to render a 3D scene:

  1. Create a Scene: Defines the 3D world.
  2. Add a Camera: Determines the viewer’s perspective.
  3. Set up a Renderer: Converts the scene into pixels displayed on the screen.
  4. Add Objects: Creates 3D models like cubes, spheres, and custom geometries.
  5. Apply Materials and Textures: Enhances the visual appearance.
  6. Add Lights: Illuminates the scene.
  7. Render the Scene: Displays the final 3D output.

Key Components of Three.js

Scene: The scene acts as a container that holds all 3D objects, lights, and cameras. In the scene, we add, manage, and organize our content.

const scene = new THREE.Scene();

Camera: The camera decides which part of the scene should be visible. The most common type of camera that mimics the human is PrespectiveCamera.

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;

Renderer: Three.js uses WebGLRenderer for the high-quality graphics, they take the scene and camera and output the visual result to the screen.

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

Mesh: The material defines the object like color, and texture whereas the Geometries define the shape of the object. When we combine them they form a visible 3D object known as mesh.

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

Lights: Lights affect how objects appear. Without lights, everything looks flat. You can use different types of lights like ambient light for general illumination, and directional light to simulate sunlight.

const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);

const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(5, 10, 7.5);
scene.add(directionalLight);

Animation Loop: For updating and rendering the scene, three.js uses the animation loop.

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

Building a Simple Three.js Project

1. Create a folder for your project (e.g., threejs-project).

Inside the folder, create the file:

  • index.html
HTML
<html>
<head>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -applesystem, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
                Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
        }
        html,
        body {
            height: 100vh;
            overflow: hidden;
            width: 100vw;
        }
        #threejs-container {
            position: block;
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <div id="threejs-container"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
    <script type="module">
        const width = window.innerWidth
        const height = window.innerHeight
        // scene
        const scene = new THREE.Scene()
        scene.background = new THREE.Color(0x262626)
        // camera
        const camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 100)
        camera.position.set(0, 0, 10)
        // cube
        const geometry = new THREE.BoxGeometry(2, 2, 2)
        const material = new THREE.MeshBasicMaterial({
            color: 0xffffff,
            wireframe: true
        })
        const cube = new THREE.Mesh(geometry, material)
        scene.add(cube)
        // renderer
        const renderer = new THREE.WebGL1Renderer()
        renderer.setSize(width, height)
        renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
        // rendering the scene
        const container = document.querySelector('#threejs-container')
        container.append(renderer.domElement)
        renderer.render(scene, camera)
    </script>
</body>
</html>

Output

Output
Three.js - JavaScript 3D Library

In this example

  • The Three.js library is included using a CDN (<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js">), and the scene is initialized with a black background color (scene.background = new THREE.Color(0x262626)).
  • A PerspectiveCamera is positioned at (0, 0, 10), and a simple cube geometry is created using BoxGeometry and MeshBasicMaterial with a wireframe effect.
  • A WebGL renderer is set up to match the screen size, and the cube is rendered within the #threejs-container div using the renderer.render() method. This displays the scene in the browser.

Features of Three.js

  • Cross-browser Compatibility: Works seamlessly across modern web browsers.
  • WebGL Abstraction: Provides an easier API for WebGL rendering.
  • Scene Graph: Helps organize objects, lights, and cameras within a scene.
  • Support for Multiple Cameras: Includes perspective and orthographic cameras.
  • Material and Shading Support: Offers a variety of built-in materials and shader capabilities.
  • Animation System: Enables keyframe-based and skeletal animations.
  • Lighting System: Supports ambient, directional, point, and spotlights.
  • Geometry and Meshes: Provides built-in geometries like cubes, spheres, and custom shapes.
  • Texture Mapping: Allows applying textures to objects.
  • Physics and Interactivity: Can be integrated with physics engines and user interactions

Applications of Three.js

  • Web-based 3D Games: Three.js is widely used for creating interactive 3D games that run directly in the browser.
  • Product Visualizations: Three.js is used in many E-commerce sites to showcase their products in 3D.
  • Data Visualization: Complex datasets can be represented visually in 3D, making it easier to understand relationships and trends.
  • Architectural Visualization: Architects and interior designers use Three.js to build 3D walkthroughs of their designs.

Three.js vs Other 3D Libraries

Feature

Three.js

Babylon.js

A-Frame

Ease of Use

Simple API for 3D rendering

Comprehensive but complex

Very beginner-friendly

Flexibility

Highly customizable

Less flexible, but feature-rich

Less flexible but very easy for the VR

Community

Large, active community

Large, active community

Smaller community

WebGL Support

Full WebGL support

Full WebGL support

Built on top of Three.js


Similar Reads