Skip to the content

Welcome to our step-by-step guide on getting started with Three.js! Whether you are a seasoned developer or a curious beginner, this post will help you understand the basics of Three.js and how to create engaging 3D graphics for your web applications. Dive in and let’s explore the exciting world of Three.js together!


Understanding Three.js :

Three.js is a powerful JavaScript library used for creating and displaying 3D computer graphics in web browsers. It provides a wide range of features for rendering 3D scenes, handling animations, applying materials and textures, and interacting with 3D objects. Three.js is built on top of WebGL, a web standard that allows for hardware-accelerated 3D graphics rendering.

 

Key features of Three.js include :

  • Scene management: Creating and managing 3D scenes with objects, lights, and cameras.

  • Geometry and materials: Generating and customizing 3D shapes, applying textures, and defining material properties.

  • Animation: Animating objects, cameras, and lights using keyframes, morph targets, and shaders.

  • Interaction: Implementing user interactions such as mouse and keyboard controls, raycasting for object picking, and collision detection.

  • Integration: Integrating 3D models from external sources like Blender or Autodesk Maya, and using plugins for physics simulations and post-processing effects.


Cube Three.js

  • Before we Start
    This imports the entire Three.js library which contains all the necessary functions and objects for 3D rendering .


  • Creating the Scene :
    This line creates a new Three.js scene Scene is empty where we can place objects, lights, and camera . It can hold elements we want to render.


  • Set up a Camera
    Creates a perspective camera The camera determines what is visible in the scene , parameters for field of view, aspect ratio, and clipping planes.


  • Create a renderer :
    WebGLRenderer is responsible for rendering the Three.js scene using WebGL, which is javascript API for rendering 3D graphics with any web browser.

  • Attach the renderer to the document :
    The canvas element where the Three.js scene will be drawn . It draws the output by appending it to body , make it visible on webpage and ready for rendering .


// Import Three.js
  import * as THREE from 'three';

// Create a scene
  const scene = new THREE.Scene();

// Set up a camera
  const camera = new THREE.PerspectiveCamera(75, window.innerWidth / 
  window.innerHeight, 0.1, 1000);

// Create a renderer and attach it to our document
  const renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

Adding 3D Object

  • Create a Cube Geometry :
    BoxGeometry is a geometry class for a rectangular cuboid with a given 'width', 'height', and 'depth'.


  • Create a Material :
    ‘MeshBasicMaterial’ is type of material in three.js that is used to create simple material with color . There are six different colors used for each side.


  • Combine them into Mesh :
    It creates a new mesh object by “THREE.Mesh” by combining a geometry and a material .Geometry variable holds the shape of the cube and Material variables holds the material apply to the cube .
    By this variables we get a 3D object  which is added to scene.


  • Add Cube to the Scene :
    Means that you are adding the cube object to the Three.js scene. The cube object is likely a mesh created using THREE.Mesh class, representing a 3D geometric shape and material cube Once added to the scene, the cube will be rendered and displayed .


// Creating cube geometry, materials, and mesh
  const geometry = new THREE.BoxGeometry( 1.3, 1.3 , 1.3 );
  const material = [ new THREE.MeshStandardMaterial({ color: 0x00ff00 }),
  new THREE.MeshStandardMaterial({ color: 0x00ffff }), 
  new THREE.MeshStandardMaterial({ color: 0x0000ff }), 
  new THREE.MeshStandardMaterial({ color: 0xffff00 }), 
  new THREE.MeshStandardMaterial({ color: 0xff00ff }), 
  new THREE.MeshStandardMaterial({ color: 0x00ffff })  
  ];
  const cube = new THREE.Mesh(geometry, material);

// Set the cube to cast shadows
  cube.castShadow = true;

// Add the cube to the scene
  scene.add(cube);

Shadow properties for Cube

  • Creating the Shadow :
    This code checks each part of the cube. If a mesh is found, it enables shadow casting for that mesh.

// Setting shadow properties for cube 
  cube.traverse(function(node){
  if(node.isMesh)
  node.castShadow = true;
  });

Creating Ground Plane

  • Creating a Plane :
    This code creates a flat plane (ground) with a size of 30x30 units, colored light gray, positioned below other objects in the scene. It's set to receive shadows to enhance realism.

  • Set Camera :
    It sets the camera's position 5 units away from the center of the scene along the z-axis . This determines how far or close the camera is to the objects in the scene when rendering. Positive values move the camera away from the scene, while negative values move it closer. Adjusting this value changes the perspective of the scene when rendered.

// Creating Ground plane and adding it to the Scene
  const groundGeometry = new THREE.PlaneGeometry( 30,30 );
  const groundMaterial = new THREE.MeshStandardMaterial({ 
  color: 0xdddddd });
  const ground = new THREE.Mesh(groundGeometry, 
  groundMaterial);
  ground.rotation.x = -Math.PI / 2; 
  ground.position.y = -1.5; 
  ground.receiveShadow = true; 
  scene.add(ground);

//Setting up Camera Position
  camera.position.z = 5;

Adding Directional Light

  • Adding Directional Light :
    Creates a directional light with a white color and having  intensity of 1setting the position to (0, 5, 0), the light source is placed at the center horizontally x-axis , 5 units above the ground vertically y-axis, and at the center of the scene depth-wise z-axis.Enables the light to cast shadows.Adds the directional light to the scene.

  • Setting ShadowMap :
    Sets the near and far plane distance for the shadow camera. This determines how close and far to the camera shadows will be rendered.


// Adding Directional Light
  const light = new THREE.DirectionalLight( 0xffffff, 1 );
  light.position.set( 0, 5, 0 ); 
  light.castShadow = true; 
  scene.add( light );

//Setting ShadowMap for renderer
  renderer.shadowMap.near = 0.5;
  renderer.shadowMap.far = 500;

Defining animation variables

  • Defining Cube Animation :
    The isRotating with value false shows that object is not rotating initially . The rotation speed shows how fast an object rotates in three.js scene .rotationDirectionx , rotationDirectionY and rotationDirectionZ are variables that determine the direction of rotation for an object along the x-axis, y-axis, and z-axis respectively in a Three.js scene. Each variable is set to 1, indicating that the rotation is initially in the positive direction along each axis. isAnimating = false indicates the object should not animate.

// Defining animation variables
  let isRotating = false;
  let rotationSpeed = 0.01;
  let rotationDirectionX = 1;
  let rotationDirectionY = 1;
  let rotationDirectionZ = 1;
  let isAnimating = false;

Creating function to start cube animation

  • Create function to start animation :
    This function animate() is called recursively using requestAnimationFrame(), continuously updating the scene's rendering. If rotation is enabled (isRotating), it adjusts the cube's rotation based on predefined speed and direction, then renders the updated scene.


// Function to continuously animate the scene
  function animate() {

// Request the browser to call this function again for the next frame
  requestAnimationFrame(animate);

// Rotate the cube if the isRotating flag is true
  if (isRotating) {

// Adjust cube rotation speed and direction on each axis
  cube.rotation.x += rotationSpeed * rotationDirectionX;
  cube.rotation.y += rotationSpeed * rotationDirectionY;
  cube.rotation.z += rotationSpeed * rotationDirectionZ;   
  }

// Render the scene using the renderer and camera setup
  renderer.render(scene, camera);

// Update performance stats if available
  stats.update()

  }

Creating function to stop cube animation

  • Create function to stop animation :
    This function stopAnimate() stops the cube from spinning and isRotating and isAnimating is set to false to it stops rotating and animating , and makes sure the cube still casts shadows in the scene.


// Function to stop animation
  function stopAnimate() {

  isRotating = false;
  isAnimating = false; 
  cube.castShadow = true;
   
  }

Creating function toggleRotation to reverses the direction of rotation

  • Create function toggle for rotation :
    This function toggleRotation() changes the direction of rotation for an object in a 3D space. Each time it's called, it reverses the rotation direction along the X, Y, and Z axes by multiplying their current values by -1. This effectively makes the object rotate in the opposite direction across all three axes.

// Function to toggle rotation direction 
  function toggleRotation() {

  rotationDirectionX *= -1;
  rotationDirectionY *= -1;
  rotationDirectionZ *= -1;

  }

Create function showShadow for shadow

  • Creating function showShadow for showing shadow :
    This function showShadow() enables shadows in a 3D scene. It sets cube.castShadow to true, allowing the cube to cast shadows. It also toggles ground.receiveShadow to switch between receiving shadows and not receiving shadows . renderer.render(scene, camera) updates the scene to reflect these shadow changes visually.

// Function to toggle shadow visibility
  function showShadow() {

// Enable the cube to cast shadows
  cube.castShadow = true;

// Toggle whether the ground plane receives shadows
  ground.receiveShadow = !ground.receiveShadow;

// Render the scene using the renderer and camera setup
  renderer.render(scene, camera);

}

Creating function ambient light to add light to the scene

  • Creating function ambient light :
    This function showAmbientLight() adds ambient light to a 3D scene using the THREE.js library. It creates a new ambient light with a white color (0xffffff) and intensity of 0.1. The light is then added to the scene, and renderer.render(scene, camera) is called to render the updated scene with ambient lighting applied. 


// Function to add ambient light to the scene
function showAmbientLight() {
  
// Create a new ambient light
  ambientLight = new THREE.AmbientLight(0xffffff, 0.1);

// Add the ambient light to the scene
 scene.add(ambientLight);

// Render the scene using the renderer and camera setup
 renderer.render(scene, camera);

}

Creating function showDirectionalLight() for realism effect in 3D

  • Creating function showDirectionalLight() :
    This function showDirectionalLight() sets up and adds a directional light source to a 3D scene using THREE.js. The light is white (0xFFFFFF) with an intensity of 1, positioned at (10, 20, 10) in the scene. Its target is set at the origin (0, 0, 0), indicating the direction it illuminates towards. Although directionalLight.castShadow is initially set to false, settings for shadow mapping are defined for higher quality: a map size of 2048x2048, and a perspective shadow camera with specific bounds and distances. After adding the light and its target are added to the scene, renderer.render(scene, camera) updates the scene with these lighting effects.



// Function to add a directional light to the scene
function showDirectionalLight() {

directionalLight = new THREE.DirectionalLight(0xFFFFFF, 1);
directionalLight.position.set(10, 20, 10);
directionalLight.target.position.set(0, 0, 0); 
directionalLight.castShadow = false;

directionalLight.shadow.mapSize.width = 2048; 
directionalLight.shadow.mapSize.height = 2048;

directionalLight.shadow.camera.left = -10;
directionalLight.shadow.camera.right = 10;
directionalLight.shadow.camera.top = 10;
directionalLight.shadow.camera.bottom = -6;
directionalLight.shadow.camera.near = 0.5; 
directionalLight.shadow.camera.far = 500; 

scene.add(directionalLight);
scene.add(directionalLight.target); 
renderer.render(scene, camera);

}

Creating function showSpotLight for focused light source in a 3D scene

  • Create function showSpotLight() :
    This function showSpotLight() adds a spotlight to a 3D scene using THREE.js. The spotlight is yellowish (0xffffbb) with an intensity of 0.5, positioned at coordinates (-1, 5, -1). It emits light within a cone defined by an angle of Math.PI / 3, (penumbra)The spotlight has edges that fade softly making the transition from light to shadow smoother. (distance) The intensity of the spotlight diminishes gradually as you move farther away from it . The spotlight casts shadows (spotLight.castShadow = true) with a bias adjustment (spotLight.shadow.bias = -0.005). A visual helper (SpotLightHelper) is also added to visualize the light's cone and shadows in the scene.



// Function to add a spot light to the scene
  function showSpotLight() {

  spotLight = new THREE.SpotLight( 0xffffbb , 0.5 );
  spotLight.position.set( -1, 5, -1 );
  spotLight.angle = Math.PI / 3;
  spotLight.penumbra = 0.05; 
  spotLight.decay = 2; 
  spotLight.distance = 200; 
  spotLight.castShadow = true;
  spotLight.shadow.bias = - 0.005;
  scene.add( spotLight );
  
  const lightHelper = new THREE.SpotLightHelper( spotLight );
  scene.add( lightHelper );

}

GUI is simplified version of a GUI library, to create a graphical interface for controlling aspects of a 3D scene.

  • Creating function GUI :
    This code uses lil.GUI, a simplified GUI library, to create a user interface for controlling a 3D scene. It sets up three folders: 'Cube' for adjusting the rotation of a cube (x, y, z), 'Camera' to control the camera's z-coordinate (0 to 20), and 'Scale' for scaling the cube (x, y, z) with an option to toggle its visibility. Each folder is automatically opened for easy access to its controls when the GUI is shown it simplifies the adjustment of scene properties.

// Create a new GUI for managing scene controls
  const gui = new GUI();

// Create a folder named 'Cube' in the GUI
  const cubeFolder = gui.addFolder( 'Cube' )

// Add controls for rotating the cube along x, y, and z axes
   cubeFolder.add(cube.rotation, 'x', 0, Math.PI * 2)
   cubeFolder.add(cube.rotation, 'y', 0, Math.PI * 2)
   cubeFolder.add(cube.rotation, 'z', 0, Math.PI * 2)
   cubeFolder.open(); // Open the 'Cube' folder by default

// Create a folder named 'Camera' in the GUI
   const cameraFolder = gui.addFolder('Camera')

// Add a control for adjusting the camera's z-coordinate  
   cameraFolder.add(camera.position, 'z', 0, 20)

// Open the 'Camera' folder by default  
   cameraFolder.open()

// Create a folder named 'Scale' in the GUI
   const cubeScaleFolder = gui.addFolder('Scale')

// Add controls for scaling the cube along x, y, and z axes
   cubeScaleFolder.add(cube.scale, 'x', 0, 10)
   cubeScaleFolder.add(cube.scale, 'y', 0, 10)
   cubeScaleFolder.add(cube.scale, 'z', 0, 10)
   cubeScaleFolder.add(cube, 'visible', true)

// Open the 'Scale' folder by default
   cubeScaleFolder.open()
  • Adding colors :
    This code defines an object obj with six color properties (color1 to color6), each represented in different formats . The gui.addColor() method is used for each color property to add color pickers to a graphical user interface (gui). These color pickers allow users to interactively select and modify the colors associated with each property, providing a convenient way to customize color settings within the scene.

    This code initializes obj with size set to 'Medium' and speed to 1. Using gui, it adds dropdown selectors for size ('Small', 'Medium', 'Large') and speed ('Slow' (0.1), 'Normal' (1), 'Fast' (5)). Users can select sizes and speeds directly via the GUI, enhancing interaction for customizing these parameters in scenes.


// Defines an object with various color properties in different formats
  obj = {

  color1: '#AA00FF',
  color2: '#a0f',
  color3: 'rgb(170, 0, 255)',
  color4: 0xaa00ff,
  color5: 0xaa00ff,
  color6: 0xaa00ff
  
  }

// Adds color pickers to the GUI for each color property in obj
  gui.addColor( obj, 'color1' );
  gui.addColor( obj, 'color2' );
  gui.addColor( obj, 'color3' );
  gui.addColor( obj, 'color4' );
  gui.addColor( obj, 'color5' );
  gui.addColor( obj, 'color6' );

// Defines a new obj object with size and speed properties
  obj = { size: 'Medium', speed: 1 };

// Adds dropdown selectors to the GUI for size and speed properties in obj
  gui.add( obj, 'size', [ 'Small', 'Medium', 'Large' ] );
  gui.add( obj, 'speed', { Slow: 0.1, Normal: 1, Fast: 5 } );

Buttons

  • Creating Buttons :
    Each button has an onclick attribute that triggers a corresponding JavaScript function

  • Rotate: Rotate button is used to toggleRotation() to toggle rotation of an object.
  • Start Animate: Start Animate button is used to startAnimate() to begin an animation loop.
  • Stop: Stop button is used to  stopAnimate() to halt the animation loop.
  • Shadow: Shadow button is used to showShadow() to toggle visibility of shadows.
  • AmbientLight: AmbientLight button is used to showAmbientLight() to toggle ambient light in the scene.
  • DirectionalLight: DirectionalLight button is used to showDirectionalLight() to toggle directional light settings.
  • SpotLight: SpotLight button is used to showSpotLight() to toggle spotlight effects.





    

    

     
   
        

   
   
     
  
    
 
    


   My First Three.js App
  


  
             

About the author

B T

comments powered by Disqus

Join Our Community

This is a promo pod

Join Our Community Become a part of our developer community. Share your projects, get feedback, and collaborate with like-minded individuals.

Your contributions help us continue creating valuable content. Consider supporting us by sharing our content.

Junagadh, Gujarat

Support Us.