Dev.to WebDev 🛠 Dev 👁 0 📖 4 min read

From ink drawing to real car: a scan-line reveal for a glTF model in Three.js

A hero section with a 3D car is easy to get wrong: a multi-megabyte model, shaders that compile for seconds, a canvas that keeps the GPU busy while nobody looks at it. This note walks through a technique that avoids all

A hero section with a 3D car is easy to get wrong: a multi-megabyte model, shaders that compile for seconds, a canvas that keeps the GPU busy while nobody looks at it. This note walks through a technique that avoids all three: the car first appears as a paper-and-ink drawing, then a red scan line runs along it and leaves the real, textured car behind. It is built with Three.js and a few lines of shader patching, and it renders only when something changes.

1. Load a small model, and load it late

The car is a single .glb file of about 2 MB. Two things keep it that small: geometry compressed with meshopt, and WebP textures. Loading needs the meshopt decoder next to the usual loader:

import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';

const loader = new GLTFLoader().setMeshoptDecoder(MeshoptDecoder);
const gltf = await loader.loadAsync('car.glb');

The page paints a static poster image first. The 3D code starts only after the load event, when the browser is idle, and the model download is preloaded at that moment, together with the libraries:

const start = () => import('./hero3d.js').then(({ initHero3D }) => initHero3D(host));
if ('requestIdleCallback' in window) requestIdleCallback(start, { timeout: 2500 });
else setTimeout(start, 300);

A guard skips the 3D entirely when it would hurt: navigator.connection.saveData, a 2g connection, or software WebGL (SwiftShader, llvmpipe), which you can detect through the WEBGL_debug_renderer_info extension. In those cases the poster simply stays.

2. One scan position, two materials

The reveal needs every fragment to know whether it is ahead of or behind the scan line. The trick is to add one varying to the built-in materials with onBeforeCompile instead of writing custom shaders from scratch:

function patch(mat, keepBehind) {
  mat.onBeforeCompile = (shader) => {
    shader.uniforms.uScan = U.uScan;            // scan position along the car (x)
    shader.vertexShader = shader.vertexShader
      .replace('#include <common>', '#include <common>\nvarying float vX;')
      .replace('#include <project_vertex>',
        '#include <project_vertex>\nvX = (uToCar * modelMatrix * vec4(transformed, 1.0)).x;');
    shader.fragmentShader = shader.fragmentShader
      .replace('#include <clipping_planes_fragment>',
        '#include <clipping_planes_fragment>\n' +
        (keepBehind ? 'if (vX > uScan) discard;' : 'if (vX < uScan) discard;'));
  };
  mat.customProgramCacheKey = () => 'scan-' + keepBehind;   // two cache keys, two programs
  return mat;
}

Each mesh gets two layers: the original PBR material, patched to keep the part behind the line, and a flat paper-coloured material plus ink edge lines, patched to keep the part ahead. As the uniform uScan moves from the rear bumper to the front, the drawing turns into the car. A small glow near the line is just a mix towards the accent colour, scaled by the distance to the line.

Because the patch uses the stock MeshStandardMaterial pipeline, lighting, tone mapping and the environment map keep working with no extra code.

3. Ink lines for free

Edges are the cheap part: EdgesGeometry(geometry, 28) finds the creases above a 28 degree angle and returns line segments you can draw with LineBasicMaterial. If the model ships its own edge nodes, use those instead and skip the computation at load.

4. Render on demand

An idle hero should cost nothing. The render loop therefore runs only while something is moving: during the scan, while easing to a new pose after scroll or mouse input, and on resize.

const tick = (t) => {
  let busy = false;
  if (scanning) { /* advance uScan, set busy = true until k >= 1 */ }
  pose.ry += (aim.ry - pose.ry) * (1 - Math.exp(-dt / 140));   // frame-rate independent easing
  if (Math.abs(aim.ry - pose.ry) > 0.0005) busy = true;
  render();
  raf = busy ? requestAnimationFrame(tick) : 0;               // stop when nothing changes
};
const wake = () => { if (!raf) raf = requestAnimationFrame(tick); };

Scroll and pointer handlers only update the target angle and call wake(). The scan itself starts through an IntersectionObserver once the hero is at least 35% visible, and with prefers-reduced-motion it is skipped: the uniform jumps to the end and one frame is drawn.

5. Small details that matter

  • Shaders in the background. The cheap drawing materials show first. The heavy PBR programs compile with renderer.compileAsync(), which uses KHR_parallel_shader_compile where it is available, so the first frame does not freeze.
  • Fake contact shadow. A canvas radial gradient used as a CanvasTexture on a transparent plane under the car costs almost nothing and grounds the model.
  • Camera framing. Compute the camera distance from the model's bounding sphere and the narrower of the vertical and horizontal fields of view, so the whole car fits any aspect ratio.
  • Pixel ratio. Cap devicePixelRatio (1.5 on small screens, about 1.75 elsewhere) instead of rendering at native 3x.
  • Tone mapping. NeutralToneMapping with a moderate environment intensity kept the brand red from washing out to pink.

Result

A real example of this approach is the hero on the home page of Details of Cars: a 1925 roadster that starts as a drawing and is scanned into a painted car, while the page stays responsive on slow connections. The model there is a CC BY licensed Alvis from Sketchfab, recoloured to fit the site.

If you try the idea yourself, start with two things: make the poster the real fallback, and measure the idle cost in the performance panel. If the GPU is busy while the page sits still, the loop is running when it should not be.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.