Back to Blog
Technicalwebglthreejs3d

3D in the Browser: How WebGL and three.js Render Models

How WebGL and three.js turn a glTF, OBJ or STL file into a lit, rotatable model in the browser: the render pipeline, GPU rasterization, light rigs, orbit controls, and why no plugin is needed.

LoopalooPublished June 19, 202611 min read

Twenty years ago, viewing a 3D model in a browser meant installing a plugin: a Java applet, a Flash widget, a Unity web player. Each one was a security liability and a maintenance headache, and they all eventually died. Today you pick a .glb file, and a lit, rotatable model appears with nothing installed. The thing that made that possible is WebGL, a browser API that gives JavaScript a direct line to your graphics card.

This post walks through what happens between "the user picks a file" and "a lit, rotatable model appears on screen." The examples use three.js, the most widely used WebGL library, and follow the standard pattern a simple model viewer uses: build a scene, parse a model file into geometry, attach materials and lights, and run a render loop.

In brief: WebGL is the low-level GPU interface, three.js is the library that makes WebGL usable by humans, and the model file is a structured list of numbers describing points in space and how to color them.

The render pipeline in a handful of objects

Almost every real-time 3D renderer, from a AAA game engine to a 200-line viewer, is organized around the same handful of concepts. three.js names them directly, which makes the structure easy to see.

ObjectWhat it isIn three.js
SceneThe container; a graph of everything to drawnew THREE.Scene()
CameraThe viewpoint and projectionPerspectiveCamera(fov, aspect, near, far)
MeshGeometry plus a materialnew THREE.Mesh(geometry, material), or built by a file loader
MaterialHow a surface responds to lightMeshStandardMaterial for physically based shading
LightWhere illumination comes fromDirectional, ambient, hemisphere, point
RendererThe thing that draws scene + camera to a canvasWebGLRenderer

A minimal setup looks like this:

import * as THREE from 'three';

const scene = new THREE.Scene();
scene.background = new THREE.Color(0x202530);

const camera = new THREE.PerspectiveCamera(
  50,               // vertical field of view, degrees
  width / height,   // aspect ratio
  0.1,              // near clip plane
  1000              // far clip plane
);
camera.position.set(3, 2, 3);

const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));

A few of those numbers carry real meaning. The field of view (50 degrees here) controls how much of the world the camera sees; wider values exaggerate perspective, like a wide-angle lens. The near and far planes (0.1 and 1000) define the depth range the GPU will bother to render. Anything closer than 0.1 units or farther than 1000 gets clipped. That range is not free: the depth buffer that decides which surface is in front has finite precision, so a near plane set absurdly small relative to the far plane causes "z-fighting", where two surfaces flicker because the GPU cannot decide which is closer.

Capping the pixel ratio is a small but deliberate choice. On a high-density phone screen, devicePixelRatio might be 3, which means rendering at 3x resolution and pushing nine times the pixels of a 1x display. Capping it at 2 keeps the image sharp while protecting the frame rate.

What a glTF or OBJ file actually contains

A 3D model file holds a description of a surface rather than a picture of it, and the format determines how much of that description is included.

An OBJ file is plain text. Each line is a small instruction: v 1.0 2.0 3.0 declares a vertex at a point in space, vt declares a texture coordinate, vn declares a normal vector, and f 1 2 3 declares a face connecting three vertices. That is essentially the whole format. It is human-readable and ancient, which is also its weakness: OBJ stores geometry, but materials live in a separate .mtl file that is easy to lose, and it has no concept of animation, scene hierarchy or compression.

A viewer has to plan for the missing .mtl. Without it, the loader falls back to a plain placeholder material, so a common approach is to walk the parsed model and give every mesh a neutral, physically based surface instead:

const neutral = new THREE.MeshStandardMaterial({
  color: 0x9a9a9a,
  metalness: 0.1,
  roughness: 0.7,
});

model.traverse((node) => {
  if (node.isMesh) node.material = neutral;
});

An STL file needs the same treatment for a different reason: it has no material concept at all. three.js's STLLoader returns a bare BufferGeometry, and you wrap it in a Mesh with whatever material you choose. Either way, the model arrives with a sensible surface to light.

A glTF file (and its binary cousin .glb) is the modern answer and is often called "the JPEG of 3D." It is a JSON scene description that references binary buffers of vertex data, and it packs in everything OBJ leaves out: a node hierarchy, PBR (physically based rendering) materials, embedded textures, skeletal animation and morph targets. The .glb variant bundles the JSON and all the binary buffers into one file, which is why most viewers prefer it. To load a file the user picked without involving a server, hand its bytes straight to GLTFLoader.parse:

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

const bytes = await file.arrayBuffer();
const gltf = await new Promise((resolve, reject) => {
  new GLTFLoader().parse(bytes, '', resolve, reject);
});
scene.add(gltf.scene);

OBJ is text, so its bytes go through a TextDecoder first and the resulting string goes to OBJLoader.parse. STLLoader and FBXLoader parse an ArrayBuffer directly. STL is geometry only (the standard for 3D printing, with no color and no units), and FBX is a proprietary Autodesk format common in game and animation pipelines. Whatever the format, everything ends up as the same thing inside three.js: a tree of meshes, each holding a BufferGeometry (typed arrays of vertex positions, normals and texture coordinates) and one or more materials.

Normals, and why a model can look flat or wrong

Lighting math needs to know which way each surface faces. That direction is the surface normal, a unit vector perpendicular to the face. Some OBJ exports omit normals entirely, and an STL stores only one normal per triangle (sometimes left as zeros). Without usable normals, lighting breaks down and the model looks flat or pitch black. The usual guard is to compute normals when they are missing:

model.traverse((node) => {
  if (node.isMesh && !node.geometry.attributes.normal) {
    node.geometry.computeVertexNormals();
  }
});

computeVertexNormals() walks the faces, averages the normals of every face that shares each vertex, and stores the result. That averaging is the difference between a sphere that looks smooth and one that looks like a stack of flat plates, but it only works when triangles actually share vertices. Many loaders, three.js's STL and OBJ loaders among them, produce "non-indexed" geometry: every triangle carries its own three copies of its corners, so a cube with 8 corners arrives as 36 position entries (12 triangles times 3). With nothing shared there is nothing to average, and the result stays faceted. To get smooth shading back, delete the per-face normals, merge the duplicate corners (three.js ships a mergeVertices helper for this), and then compute normals.

From triangles to pixels: GPU rasterization

Once geometry and materials exist, the renderer's job is to turn 3D triangles into 2D pixels. This is the part WebGL exposes directly, and it is worth understanding even when a library hides it.

Every frame, for every triangle, the GPU runs two small programs called shaders. The vertex shader runs once per vertex and transforms its position through a chain of matrices: model space (the object's own coordinates) to world space (where it sits in the scene) to view space (relative to the camera) to clip space (the camera's projection). three.js builds those matrices for you; object.updateMatrixWorld() keeps the world matrices current, and camera.updateProjectionMatrix() rebuilds the projection after you change the field of view or aspect ratio.

After the vertex shader places the three corners of a triangle on screen, rasterization fills in the pixels between them. For each covered pixel, the GPU runs the fragment shader, which computes the final color. This is where the material and lights meet: a MeshStandardMaterial runs a PBR lighting equation that combines the surface's base color, its metalness and roughness, the surface normal and every light in the scene to produce one RGB value per pixel.

The reason this stays smooth is parallelism. A modern GPU has thousands of cores, and rasterization is embarrassingly parallel: every pixel's color is computed independently, so the hardware works through large batches of them at once. A model with, say, 50,000 triangles is not drawn one triangle at a time on the CPU. The vertex data is uploaded to GPU memory once, and the GPU chews through it. The browser's only job each frame is to issue a handful of draw calls and let the silicon do the work.

Soft shadows add a second pass:

renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;

Shadow mapping renders the scene a second time from each shadow-casting light's point of view, recording depth into a texture. During the main pass, each pixel checks that depth map to ask "is something between me and the light?" PCF (percentage-closer filtering) samples the map at several nearby points and averages the result, which softens the otherwise jagged shadow edge. In three.js, a light only casts shadows when its castShadow is set, and each mesh opts in with castShadow and receiveShadow.

Lighting presets are light rigs

There is no single "correct" light in a 3D scene, only a rig of several lights balanced against each other. The classic studio arrangement is the three-point setup from photography: a strong key light, a weaker fill light on the opposite side to soften shadows, and a back light to separate the subject from the background, usually over a little ambient light so nothing goes completely black:

scene.add(new THREE.AmbientLight(0xffffff, 0.4));       // base level everywhere

const key = new THREE.DirectionalLight(0xffffff, 1.0);  // main light
key.position.set(5, 5, 5);
key.castShadow = true;
scene.add(key);

const fill = new THREE.DirectionalLight(0xffffff, 0.3); // softens the key's shadows
fill.position.set(-5, 0, -5);
scene.add(fill);

const rim = new THREE.DirectionalLight(0xffffff, 0.2);  // outlines the silhouette
rim.position.set(0, 5, -5);
scene.add(rim);

Other rigs follow the same idea with different ingredients. An outdoor look pairs a HemisphereLight (sky color from above, ground color from below) with a warm directional "sun". A dramatic product shot uses a dim ambient light and a single PointLight with a falloff distance, so the model emerges from near darkness. A flat rig is just one full-strength AmbientLight, which removes all shading and shows pure base color, useful for inspecting geometry without lighting getting in the way. Switching rigs means removing the old lights from the scene and adding the new ones; nothing about the model changes.

Orbit controls and the render loop

A static render is not a viewer. The interaction (drag to rotate, scroll to zoom, right-drag to pan) comes from three.js's OrbitControls, an add-on that translates mouse and touch events into camera movement around a target point.

import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';

const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;

Damping is the detail that makes it feel good. With enableDamping on, releasing the mouse does not stop the camera instantly; it glides to a halt over a few frames, which reads as momentum. That smoothing requires controls.update() to be called every frame, which brings us to the render loop:

let frameId;

function animate() {
  frameId = requestAnimationFrame(animate);
  controls.update();              // apply damping and auto-rotate
  renderer.render(scene, camera);
}
animate();

// When the viewer is torn down:
// cancelAnimationFrame(frameId); controls.dispose(); renderer.dispose();

requestAnimationFrame is the right tool here, not setInterval. The browser calls it in step with the display's refresh (typically 60Hz, higher on some monitors), pauses it when the tab is in the background to save battery, and never schedules a frame faster than the screen can show it. The loop's whole job is to update the controls and then draw the scene from the camera. That single render() call is what triggers the GPU rasterization described above.

Saving a screenshot has one well-known trap. By default, WebGL may clear the drawing buffer once a frame has been shown, so calling canvas.toDataURL() from a button click can return a blank image. Either create the renderer with preserveDrawingBuffer: true (at a small cost in memory and speed) or call renderer.render() and read the canvas immediately afterwards, in the same task.

A good viewer also frames each model automatically. Model files come in wildly different units (millimeters for a 3D print, meters for a building), so the viewer measures the model's bounding box, recenters it on the origin, and scales it to a standard size before placing the camera:

const box = new THREE.Box3().setFromObject(model);
const size = box.getSize(new THREE.Vector3());
const center = box.getCenter(new THREE.Vector3());

model.position.sub(center);              // move the model's center to the origin
const largest = Math.max(size.x, size.y, size.z);
const holder = new THREE.Group();
holder.add(model);
holder.scale.setScalar(largest > 0 ? 2 / largest : 1); // fit in about 2 units
scene.add(holder);

Wrapping the model in a group means the scale is applied around the already-centered model, so it stays centered at any size. With that in place, a tiny 3D-printed bolt and a building-sized architectural model both show up at a sensible size.

Why it all runs locally with no plugin

Two properties make this work without a server round trip or an install. First, WebGL is a built-in browser API backed by the GPU already in the machine. There is nothing to download, because the rendering hardware and its driver are already present and the browser exposes them through a standard interface. Second, the entire pipeline above runs on data the browser already has in memory. A viewer can read the chosen file with file.arrayBuffer(), parse it in JavaScript and upload the resulting geometry to the GPU. The file never has to go anywhere, which is good for privacy (your model stays on your machine) and for speed (no upload, no wait).

There are limits. Parsing happens on the CPU, so a multi-hundred-megabyte FBX will take a moment and a chunk of memory; the GPU can only hold so much geometry; and very high triangle counts will eventually drop the frame rate on a weak integrated GPU. For the great majority of models people actually want to inspect, those limits are far away, and the GPU's parallelism keeps the orbit smooth.

Try it

To see the pipeline in action, open the 3D Model Viewer on Loopaloo. Pick a .glb, .gltf, .obj, .stl or .fbx file, switch between the studio, outdoor, dark and flat lighting presets, and toggle wireframe to see the raw triangle mesh. The info panel shows the numbers from this post side by side: distinct vertices, position entries and triangles, plus whether the surface is closed, which matters if you plan to 3D print it. Everything renders on your own GPU, in your own browser, with nothing uploaded and nothing installed.

Related Tools

Related Articles