Three.js Toon & Cel Shading (Outlines, Rim Light, Hatching)
Non-photorealistic rendering in Three.js comparing MeshToonMaterial gradient maps, a custom cel shader with rim light and hard specular, and screen-space cross-hatching, all with inverted-hull outlines.
Key topics: three.js toon shader, cel shading, npr, outline shader, hatching, meshtoonmaterial
Game Over
What this code does
- Gradient Map: `MeshToonMaterial` looks up lighting in an N-pixel nearest-filtered texture to get flat tone bands.
- Inverted Hull: a back-face copy pushed out along normals (scaled by distance) draws a constant-width outline.
- Custom Cel: half-Lambert lighting is quantized with floor(), with a thresholded specular dot and rim light.
- Hatching: darker tones add more screen-space line layers at different angles, a tonal art map.
- Shared Geometry: outline and body reuse one geometry, so outlines cost one extra draw per object.
- Controls: technique, tone steps, outline width and color, rim light and spin.
Related Demos
Continue Learning
JavaScript Implementation
// Cel shading with a 3-step gradient map + inverted-hull outline
const gradient = new THREE.DataTexture(new Uint8Array([80, 170, 255]), 3, 1, THREE.RedFormat)
gradient.minFilter = gradient.magFilter = THREE.NearestFilter
gradient.needsUpdate = true
const geometry = new THREE.TorusKnotGeometry(0.7, 0.26, 200, 32)
const body = new THREE.Mesh(geometry, new THREE.MeshToonMaterial({ color: 0xf97316, gradientMap: gradient }))
const outline = new THREE.Mesh(geometry, new THREE.ShaderMaterial({
side: THREE.BackSide, // only the far side of the inflated hull shows → a silhouette line
vertexShader: 'void main () { vec3 p = position + normal * 0.03; gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0); }',
fragmentShader: 'void main () { gl_FragColor = vec4(0.1, 0.08, 0.14, 1.0); }'
}))
scene.add(body, outline)
scene.add(new THREE.DirectionalLight(0xffffff, 2.5), new THREE.AmbientLight(0xffffff, 0.3))