DEV Community

kishor sutradhar
kishor sutradhar

Posted on

Today’s new knowledge #5 (Three.js)

Today's Overview:

Hello again, everyone! ❤️❤️ Hope you're all doing great! Today, I began learning THREE.js to create 3D effects for websites.I have some knowledge in 3D modeling and game development which allowed me to understand THREE.js concepts quickly. I aim to incorporate at least one 3D effect into my portfolio. Here's a summary of what I've learned in THREE.js.

Today’s new knowledge #5

Three.js:

For those who doesn't know Three.js is a popular JavaScript library that simplifies creating and displaying 3D graphics in web applications using WebGL. It provides tools and abstractions to build and animate 3D scenes, making it easier to work with complex graphics without writing WebGL code directly.

so I start from the basic of three js. The first part is the Scene

Scene:

The core of a Three.js project starts with a scene. A scene acts as a container for all objects, including geometries, lights, cameras, and other elements.

const scene = new THREE.Scene();
Enter fullscreen mode Exit fullscreen mode

Cameras:

In Three.js, cameras are essential for rendering the scene. Cameras determine what portion of the 3D scene is visible to the user. there are two main cameras that are used in the scene

1. PerspectiveCamera

Mimics the perspective of human vision, where objects farther away appear smaller. Commonly used in games and realistic 3D scenes.

const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
Enter fullscreen mode Exit fullscreen mode

fov: Field of view in degrees (vertical).
aspect: Aspect ratio (width divided by height of the viewport).
near: Near clipping plane (objects closer will not be rendered).
far: Far clipping plane (objects farther away will not be rendered).

2. OrthographicCamera

Maintains the same size for objects regardless of distance, without perspective distortion. Common in 2D games, CAD applications, or UI elements.

const camera = new THREE.OrthographicCamera(left, right, top, bottom, near, far);
Enter fullscreen mode Exit fullscreen mode

left, right: Horizontal clipping planes.
top, bottom: Vertical clipping planes.
near, far: Clipping planes for depth.

there are other cameras in three js like ArrayCamera, CubeCamera or StereoCamera. you can learn more from the documentation about those.

Geometries

Then i stated learning about Geometries. These are the basic shapes (e.g., cubes, spheres, planes) used to construct 3D objects. some of the example are BoxGeometry CapsuleGeometry CircleGeometry CylinderGeometry.you can learn more from the documentation.

const geometry = new THREE.BoxGeometry();
Enter fullscreen mode Exit fullscreen mode

if you want to add custom 3D object from a 3d modeling software like blender, maya. The GLTFLoader is a popular choice for modern 3D models.Export your model as a .glb or .gltf file. Load it into the Three.js scene.

import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';

const loader = new GLTFLoader();
loader.load('path/to/model.glb', (gltf) => {
    const model = gltf.scene;
    model.scale.set(1, 1, 1); // Adjust size
    model.position.set(0, 0, 0); // Position in the scene
    scene.add(model);
}, undefined, (error) => {
    console.error('An error occurred loading the model', error);
});
Enter fullscreen mode Exit fullscreen mode

Materials

Define how the surfaces of objects appear when rendered. Materials control properties like color, texture, opacity, reflectivity, and how the object interacts with lights in the scene.

  • Basic Material A simple material that does not react to lighting. It's always fully visible. Great for debugging or non-shaded visuals like 2D-like graphics.
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
Enter fullscreen mode Exit fullscreen mode
  • Standard Material (PBR) Physically Based Rendering (PBR) material for realistic surfaces. Reacts realistically to lighting. High-quality visuals for realistic simulations, games, and AR/VR.
const material = new THREE.MeshStandardMaterial({ color: 0x888888, metalness: 0.5, roughness: 0.2 });
Enter fullscreen mode Exit fullscreen mode

metalness: Controls how metallic the material appears (0 = non-metallic, 1 = metallic).
roughness: Defines surface smoothness (0 = smooth, 1 = rough).
map: Adds textures.
normalMap: For detailed surface bumps.
envMap: Adds reflections from the environment.

  • Physical Material Similar to MeshStandardMaterial but includes advanced PBR properties like clear coats and sheen. For ultra-realistic surfaces like cars, gemstones, or coated objects.
const material = new THREE.MeshPhysicalMaterial({ clearcoat: 1.0, reflectivity: 0.9 });
Enter fullscreen mode Exit fullscreen mode

there are meterial like those.you can learn more from the documentation.

Texture mapping

Texture mapping in Three.js is a technique to apply images or patterns (textures) onto the surface of 3D objects to make them visually realistic or stylized. Three.js provides the TextureLoader to load textures into your scene.

const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load('path/to/texture.jpg');

const material = new THREE.MeshStandardMaterial({
    map: texture, // Assign texture to material
});
Enter fullscreen mode Exit fullscreen mode

Textures can be used in various ways to enhance materials:
Color Texture (map): The base texture that covers the surface.
Normal Map: Adds surface details like bumps without modifying geometry.
Bump Map: Similar to a normal map but simpler.
Displacement Map: Modifies geometry vertices for real surface bumps.
Roughness Map: Controls the roughness of the surface for reflections.
Metalness Map: Dictates metallic appearance.
Alpha Map: Creates transparency on parts of the surface.
Ambient Occlusion Map: Adds shadows for depth perception.

Mesh

In Three.js, a Mesh is a 3D object created by combining geometry with a material. Meshes are fundamental in creating visual objects in a Three.js scene.

const cube = new THREE.Mesh(geometry, material); // Combine into a mesh
scene.add(cube); // Add the mesh to the scene
Enter fullscreen mode Exit fullscreen mode

Lights

In Three.js, lights are essential for illuminating a scene, giving depth, and highlighting the materials applied to objects. They simulate real-world lighting conditions to create realistic or stylized effects in 3D environments.

Ambient Light

Provides uniform lighting across the entire scene without direction. Does not create shadows. Basic fill light or to soften shadows.

const ambientLight = new THREE.AmbientLight(0xffffff, 0.5); // Color and intensity
scene.add(ambientLight);
Enter fullscreen mode Exit fullscreen mode

Directional Light

Mimics sunlight by casting parallel rays in a specific direction. Can cast shadows.

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

// Enable shadows
directionalLight.castShadow = true;
directionalLight.shadow.mapSize.width = 1024; // Higher values for better quality
directionalLight.shadow.mapSize.height = 1024;
Enter fullscreen mode Exit fullscreen mode

Point Light

Emits light in all directions from a single point, like a bulb. Can cast shadows.

const pointLight = new THREE.PointLight(0xffffff, 1, 100); // Color, intensity, distance
pointLight.position.set(5, 5, 5);
scene.add(pointLight);

// Enable shadows
pointLight.castShadow = true;
Enter fullscreen mode Exit fullscreen mode

Spotlight

Emits a cone of light, like a flashlight or stage spotlight. Can cast sharp, focused shadows.

const spotlight = new THREE.SpotLight(0xffffff, 1);
spotlight.position.set(5, 10, 5);
spotlight.angle = Math.PI / 6; // Cone angle
spotlight.penumbra = 0.2; // Soft edges
scene.add(spotlight);

// Enable shadows
spotlight.castShadow = true;
Enter fullscreen mode Exit fullscreen mode

Environment Lighting

Uses an HDR texture to create realistic ambient lighting and reflections.
Does not require specific light objects but uses a texture.

const loader = new THREE.TextureLoader();
const envTexture = loader.load('path/to/hdr.jpg');
scene.environment = envTexture; // Applies to all reflective materials
Enter fullscreen mode Exit fullscreen mode

There are various types of lights in the documentation.

Animation

In Three.js, animations are a powerful way to bring 3D scenes to life, enabling movement, transformations, or dynamic changes in objects, lights, or cameras.

Animating Using the Animation Loop

The render/animation loop updates the scene continuously, enabling you to animate objects frame by frame.

function animate() {
    requestAnimationFrame(animate); // Loop the animation

    mesh.rotation.x += 0.01; // Rotate on the X-axis
    mesh.rotation.y += 0.01; // Rotate on the Y-axis

    renderer.render(scene, camera); // Render the scene
}
animate();
Enter fullscreen mode Exit fullscreen mode

Using GSAP for Advanced Animations

GSAP (GreenSock Animation Platform) is a powerful library for smooth and complex animations.

gsap.to(mesh.position, {
    x: 5,
    duration: 2,
    ease: "power1.inOut", // Easing function
    onComplete: () => console.log('Animation complete!'),
});
Enter fullscreen mode Exit fullscreen mode

there are other way to animate as well for that read documentation.

renderer

In Three.js, rendering is the process of converting a 3D scene into a 2D image or series of images for display. This involves calculating light, shadows, materials, and transformations based on the current camera perspective and displaying the result to the screen.

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);  // Add canvas to DOM

function animate() {
    requestAnimationFrame(animate);  // Repeats the animation loop
    renderer.render(scene, camera);  // Renders the scene from the camera's perspective
}
animate(); 
Enter fullscreen mode Exit fullscreen mode

randerer is used for Post-Processing and Antialiasing. Post-processing allows you to apply effects like bloom, depth of field, or color grading after the scene has been rendered. It’s achieved using the EffectComposer and shaders. Helps smooth jagged edges (aliasing) in the rendered image by averaging colors around edges.

const composer = new THREE.EffectComposer(renderer);
const renderPass = new THREE.RenderPass(scene, camera);
composer.addPass(renderPass);
const renderer = new THREE.WebGLRenderer({ antialias: true });
Enter fullscreen mode Exit fullscreen mode

Conclusion

Those are the things i learn today that are new. hope you guys like it. see you soon. Thank you.

Top comments (2)

Collapse
 
gladiatorsbattle profile image
Gladiators Battle

Wow, this is such an informative and well-structured overview of THREE.js! 🚀 It's impressive how you've broken down the core concepts, from scenes and cameras to animations and rendering. Your explanations make it approachable even for beginners while highlighting the library's potential for advanced 3D work. Can't wait to see how you incorporate these skills into your portfolio. Keep sharing your progress! 🙌 #ThreeJS #WebDev #3DModeling

Collapse
 
kishor_sutradhar_d2503ac4 profile image
kishor sutradhar

Thanks for the review. I incorporate how I am learning THREE.js and share my knowledge. I think blogging helps me to understand those concepts better. Thanks again for the encouragement.