Exploring the World of 3D Graphics

Exploring the World of 3D Graphics

Three.js Journey (Part 1)

Introduction

Greetings, fellow developers! I'm Mukund, an enthusiastic Full-Stack Web Developer, and I'm thrilled to embark on this exciting journey into the captivating realm of Three.js with all of you. In this debut blog post, I can't wait to take you on a thrilling ride through my exploration of 3D computer graphics right within the web browser, all thanks to the powerful WebGL-based library - Three.js.

Understanding Three.js

Three.js - a versatile JavaScript library that empowers developers to craft mesmerizing 3D computer graphics right in the web browser using WebGL. As you may know, the web browser alone cannot directly interact with the GPU through OpenGL. However, the ingenious solution came in the form of WebGL, released in 2011, which acts as a conduit between our code and the GPU, enabling efficient graphics rendering on the web.

However, working directly with raw WebGL involves using GLSL (OpenGL Shading Language), a unique language that can be a challenge to master, especially for those unfamiliar with it. That's where the magic of Three.js shines through! It acts as a bridge between our familiar JavaScript code and the WebGL world. With Three.js, we can write our code in JavaScript, and under the hood, Three.js seamlessly converts it into GLSL, simplifying the process of creating impressive 3D visuals.

Image Source - https://www.youtube.com/watch?v=6AHpdQCrf_Q&ab_channel=WaelYasmina

Let's Get Our Hands Dirty

No more theory, my friends! It's time to roll up our sleeves and immerse ourselves in the practical wonders of Three.js. Throughout this captivating blog series, I'll share insightful code snippets, detailed explanations, and who knows, we might even indulge in some interactive demos to showcase the awe-inspiring potential of these robust tools.

(Note: I'm assuming you're familiar with the basics of HTML, CSS, JS, and Node.js)

Setting the Stage: Project Setup

Let's kick things off by creating a dedicated folder for our exciting Three.js project. Follow these steps:

  1. Create a new folder: Open your command line and type:
mkdir threejs-project
cd threejs-project
  1. Initialize your project: Continue in your command line:
npm init -y
npm install three
npm install -D vite

Now, let's make a few crucial adjustments to your package.json file and create a vite.config.js file. Here's the modified package.json:

{
  "name": "threejs-project",
  "private": true,
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "devDependencies": {
    "vite": "^4.4.8"
  },
  "dependencies": {
    "three": "^0.155.0"
  }
}

And the content of your vite.config.js:

import { defineConfig } from "vite";
export default defineConfig({
  root: "src/",
  publicDir: "../static/",
  base: "./",
  server: {
    host: true,
  },
  build: {
    outDir: "../dist",
    sourcemap: true,
    emptyOutDir: true,
  },
});

Creating the Foundation: HTML and JavaScript

With the setup in place, let's create the foundation for our project. Within your project folder, create a src directory and add an index.html file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Threejs Project</title>
    <style>
      body {
        margin: 0;
        padding: 0;
      }
      * {
        box-sizing: border-box;
      }
    </style>
  </head>
  <body>
    <canvas class="webgl"></canvas>
    <script src="script.js" type="module"></script>
  </body>
</html>

Now, let's dive into the JavaScript magic by creating the script.js file inside the src directory:

// We import three using namespace as shown
import * as THREE from "three";

// Then we create a scene using THREE.Scene()
const scene = new THREE.Scene();

/**
 * After Creating a scene we can add objects to it
 * like Box, Sphere, Plane, etc.
 * We can also add lights and cameras to the scene
 */

/**
 * For now we will add a red cube to the scene and a camera
 */

/**
 * To add a cube we need to create a geometry and a material
 * Geometry is the shape of the object
 * Material is the color of the object
 * We can also add textures to the material to make it look more realistic
 * we will cover that in later posts
 */

/**
 * To create a geometry we use THREE.BoxGeometry()
 * First parameter is the width of the cube
 * Second parameter is the height of the cube
 * Third parameter is the depth of the cube
 */
const geometry = new THREE.BoxGeometry(1, 1, 1);

/**
 * To create a material we use THREE.MeshBasicMaterial()
 * We provide a color to the material by passing an object and
 * setting the color property.
 * You can pass color in hex format or in rgb format as shown
 */
const material = new THREE.MeshBasicMaterial({ color: 0xff0000 });

/**
 * Now we create a mesh using THREE.Mesh()
 * Mesh is an object that takes a geometry and applies a material to it
 * and we add the mesh to the scene by using scene.add()
 */
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

/**
 * Sizes
 * We create a sizes object to store the width and height of the canvas
 */
const sizes = {
  width: 800,
  height: 600,
};

/**
 * Now we create a camera
 * For creating a camera we use THREE.PerspectiveCamera()
 * First parameter is the field of view
 * Second parameter is the aspect ratio
 * Third parameter is the near clipping plane
 * Fourth parameter is the far clipping plane
 *
 * After creating a camera we set the position of the camera
 * using camera.position
 * and we add the camera to the scene using scene.add()
 *
 * FOV is the extent of the scene that is seen on the display
 * at any given moment. The value is in degrees.
 * Aspect Ratio is the ratio of width and height of the display area.
 * Near Clipping Plane is the minimum distance of the camera from the object.
 * Far Clipping Plane is the maximum distance of the camera from the object.
 */
const camera = new THREE.PerspectiveCamera(
  75,
  sizes.width / sizes.height,
  0.1,
  1000
);
camera.position.z = 3;
scene.add(camera);

/**
 * Renderer is used to render the scene using the camera
 * We create a renderer using THREE.WebGLRenderer()
 * It takes an object as a parameter and we pass the canvas property
 * Here canvas is the canvas element in the html file
 * We set the size of the renderer using renderer.setSize()
 *
 * After creating a renderer we render the scene using renderer.render()
 * It takes the scene and the camera as parameters
 */

const canvas = document.querySelector(".webgl");
const renderer = new THREE.WebGLRenderer({
  canvas: canvas,
});
renderer.setSize(sizes.width, sizes.height);

renderer.render(scene, camera);

Bring Your Creation to Life: Running the Project

With your script.js and index.html masterpieces in place, it's time to breathe life into your creation:

  1. In your command line, navigate to your project folder and run the development server:
npm run dev

VITE v4.4.8  ready in 172 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: http://<ip-address>:5173/
  ➜  Network: http://<ip-address>:5173/
  ➜  press h to show help
  1. Open your web browser and venture to localhost:5173. Behold, a vibrant red cube awaits your gaze!

Tutorial 1 Code: GitHub Link

Check out more about Three.js: https://threejs.org/

Conclusions

This is just the beginning of my journey into the enchanting world of Three.js, and I'm beyond excited to share every step of it with all of you. In the upcoming blog posts, I'll document my progress, discuss challenges I faced, and hopefully, inspire some of you to embark on your 3D web development quests.

So, buckle up, stay tuned, and together, let's create an extraordinary array of magical 3D experiences! 🚀