DEV Community

Cover image for Intro to WebGL & Three.js
Oryam
Oryam

Posted on

Intro to WebGL & Three.js

TL;DR - 3D in the browser is awesome, you should at least give it a try 🚀

Why read this?

As the internet becomes increasingly interactive and immersive, 3D modeling has emerged as a valuable skill for web developers and designers. With the ability to create and display complex 3D objects and scenes in real-time, 3D modeling can enhance the visual appeal and interactivity of web applications and games, as well as provide new opportunities for creative expression and storytelling. Whether you're a seasoned developer or just starting out, learning about 3D modeling on the web can open up new possibilities for your projects and help you stay at the forefront of web development trends. In this post, we'll focus on some of the basics of 3D modeling on the web and in general.

Intro to general 3D

To understand WebGL, it's helpful to have a basic understanding of 3D modeling.

3D modeling is the process of creating a three-dimensional representation of an object or scene using specialized software. This involves creating a mesh of polygons that define the shape of the object, as well as applying textures and materials to give it color, texture, and other visual properties.

The 3d rendering pipeline

  1. We start with a Vertex that identified by it's x, y and z coordinates
  2. The Vertices are connected together to create triangles named Primitives. They then connected to each other to form a more complex shapes,
  3. A light source point at them to create the appearance of shadows and depth, Fragment
  4. The 3d vector graphic converted to projection of 2d pixels on the screen (rendering)

3d rendering pipeline vertex to pixels

In low graphics we can notice where the fragments
low graphics example

Shaders are the functions that tell the computer how to render the fragments on the screen, something the CPU can't handle by itself, which is why we use the graphics processing unit (GPU).

What is WebGL

WebGL stands for Web Graphics Library and is a JavaScript API that allows you to render 3D graphics in the browser without the need for plugins. It is based on the OpenGL ES 2.0 specification and is supported by all modern web browsers.

In order to render 3D models in a web browser, WebGL uses the GPU of the computer to perform complex calculations and render the graphics in real-time. This makes it possible to create interactive and immersive 3D web applications, such as games, simulations, and virtual reality experiences.

While writing this post the new WebGPU API is coming out.

To make the connection between the script and the DOM we use the HTML canvas element.

  <body>
    <canvas id="app"></canvas>
    <script src="src/index.js"></script>
  </body>
Enter fullscreen mode Exit fullscreen mode

Why not to use WebGL API directly

While it's certainly possible to use the WebGL API directly to create 3D graphics in a web browser, doing so can be quite complex and time-consuming. WebGL is a low-level API that requires you to write shader code in GLSL (OpenGL Shading Language) to define how objects should be rendered, as well as manage low-level details such as buffers, textures, and framebuffers.

This can be challenging even for experienced developers, and can lead to code that is difficult to read, maintain, and debug. Additionally, using WebGL directly can be less efficient than using a higher-level library such as Three.js, as it requires you to perform many low-level operations manually that a library would handle for you.

For example, to create a simple box you'll need around 180 lines of code

3d box rotating

Using a library like Three.js provides a number of benefits over using WebGL directly. Three.js provides a simplified and user-friendly interface for working with 3D graphics, abstracting away many of the low-level details of WebGL and providing a range of useful features and tools for building 3D applications. This can make it much easier to get started with 3D graphics on the web, and allows you to focus on the creative aspects of your application rather than the low-level details of WebGL.
And just for the demonstration to create the same cube from before it will take us about only 30 lines of code (and much more understandable).

import * as THREE from "three";

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

const renderer = new THREE.WebGLRenderer({
  canvas: document.getElementById("app")
});

renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
camera.position.setZ(2);
renderer.render(scene, camera);

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

const animate = () => {
  requestAnimationFrame(animate);
  cube.rotation.x += 0.01;
  cube.rotation.y += 0.005;
  cube.rotation.z += 0.005;

  renderer.render(scene, camera);
};

animate();
Enter fullscreen mode Exit fullscreen mode

In the next part I’ll go more hands on in Three.js and what are the Scene, Renderer and Camera.

Here are some awesome example of Three.js:

Top comments (1)

Collapse
 
yarivshamash profile image
Yariv Shamash

Super nice and straight forwards!