Floating Bokeh Orbs & Depth of Field: Canvas Optics, Chromatic Aberration & Blur Guide

The Quick Answer

Cinematic bokeh in HTML5 Canvas simulates physical camera lenses by mapping each particle to a 3D Z-depth coordinate. The Circle of Confusion (CoC) equation determines orb radius and blur amount relative to a dynamic focal plane, while polygonal aperture paths, radial gradient falloffs, and RGB chromatic aberration fringing reproduce authentic optical lens characteristics at 60 FPS.

Interactive Demo Live Preview
✨ Move cursor vertically to rack focal plane depth

Step 1: Circle of Confusion (CoC) Optical Physics

In optical physics, bokeh discs expand when light points move further away from the lens focal plane. The diameter of the Circle of Confusion is calculated as: CoC = |d_object - d_focus| / (d_object · N), where N is the lens f-number aperture and d_focus is the current focal distance.

bokeh-optics.js
class LensSimulator {
  constructor(focalLength = 50, fNumber = 1.4, focalPlane = 300) {
    this.f = focalLength;
    this.n = fNumber;
    this.focusZ = focalPlane;
  }

  calculateCoC(particleZ) {
    // Distance from focal plane
    const deltaZ = Math.abs(particleZ - this.focusZ);
    // Base circle of confusion diameter in pixels
    const coc = (deltaZ / (particleZ * this.n)) * this.f * 1.8;
    // Particles directly on the focal plane are pin-sharp; far away orbs are wide discs
    return Math.max(3, Math.min(coc, 85));
  }
}

Step 2: Polygonal Aperture Blades and Ring Falloffs

High-end camera lenses do not produce perfect circles; their mechanical aperture diaphragms (typically 6, 7, or 9 blades) produce rounded hexagons or nonagons with brighter outer rings (spherical aberration). We generate parametric polygon paths with custom radial gradient shaders.

aperture-polygon.js
function drawApertureBokeh(ctx, x, y, radius, blades, color, alpha) {
  const step = (Math.PI * 2) / blades;
  ctx.save();
  ctx.translate(x, y);

  // Optical radial gradient with characteristic bright outer rim
  const grad = ctx.createRadialGradient(0, 0, radius * 0.4, 0, 0, radius);
  grad.addColorStop(0, `rgba(${color}, ${alpha * 0.15})`);
  grad.addColorStop(0.7, `rgba(${color}, ${alpha * 0.35})`);
  grad.addColorStop(0.92, `rgba(${color}, ${alpha * 0.8})`);
  grad.addColorStop(1, `rgba(${color}, 0)`);

  ctx.beginPath();
  for (let i = 0; i < blades; i++) {
    const angle = i * step;
    const px = Math.cos(angle) * radius;
    const py = Math.sin(angle) * radius;
    if (i === 0) ctx.moveTo(px, py);
    else ctx.lineTo(px, py);
  }
  ctx.closePath();
  ctx.fillStyle = grad;
  ctx.fill();
  ctx.restore();
}

Step 3: Chromatic Lens Aberration and Interactive Rack Focusing

High-speed prime lenses exhibit longitudinal chromatic aberration, causing magenta fringing in front of the focus plane and cyan/green fringing behind it. We offset the red and blue color channels slightly in screen space and bind cursor scrolling to rack the focal plane dynamically.

bokeh-engine.js
function renderBokehField(ctx, orbs, lens, mouseFocusZ) {
  lens.focusZ += (mouseFocusZ - lens.focusZ) * 0.08; // Smooth rack focus

  // Sort back-to-front
  orbs.sort((a, b) => b.z - a.z);

  for (const orb of orbs) {
    const coc = lens.calculateCoC(orb.z);
    const alpha = Math.max(0.15, Math.min(0.75, 1 - (coc / 100)));

    // Chromatic edge offset
    ctx.globalCompositeOperation = 'screen';
    // Red channel offset left
    drawApertureBokeh(ctx, orb.x - 1.2, orb.y, coc, 7, '255, 70, 140', alpha * 0.6);
    // Blue/Cyan channel offset right
    drawApertureBokeh(ctx, orb.x + 1.2, orb.y, coc, 7, '56, 189, 248', alpha * 0.6);
  }
  ctx.globalCompositeOperation = 'source-over';
}

Next-Level Addons: Elevating Your Implementation

Take this technique further by combining it with complementary design token studios and animation tools:

1. Aperture Blade Polygon Synthesis

Simulates mechanical camera diaphragms with 6 to 9 polygonal aperture blades and spherical aberration bright-rim outer gradients.

2. Depth of Field Focal Plane Shifting

Dynamically computes Circle of Confusion blur radii for all orbs based on interactive camera focus distance modulation.

3. OKLCH Chromatic Edge Fringing

Splits red, green, and blue spectral channels along lens edge boundaries to reproduce authentic glass dispersion and chromatic aberration.

Chaam
Chaam's Pro Tip

Here's my golden rule when implementing this in production: test across multiple devices and browsers early. Keep your DOM hierarchy shallow, optimize assets with modern formats (like WebP/AVIF), and verify keyboard navigation for accessibility.

Why I Built the Mesh Gradient Studio

I got tired of guessing values and testing browser quirks in DevTools, so I built this tool to tweak and preview values in real time with 1-click code export.

Open in Mesh Gradient Studio ↗

Frequently Asked Questions

Practical answers to common implementation questions, browser quirks, and performance tips.

What is the Circle of Confusion (CoC) and how is it used in web graphics?

In optical physics, the Circle of Confusion is the diameter of the blurred circular image produced when a point of light is out of focus on the image sensor. In web graphics and Canvas simulations, we calculate CoC based on the distance between each particle's 3D Z coordinate and the camera focal plane to dynamically scale and blur orbs.

Why do bokeh discs have bright outer rims instead of solid flat colors?

Bright rims on out-of-focus highlights are caused by spherical aberration in real optical lens glass elements, where rays passing through the outer perimeter of the lens converge at slightly different angles than central paraxial rays. Replicating this using radial gradient stops gives canvas bokeh realistic visual depth.

How does the screen blend mode enhance bokeh overlapping?

Setting `ctx.globalCompositeOperation = "screen"` ensures that when multiple out-of-focus light discs overlap, their RGB values add together logarithmically without clipping into opaque white blocks. This replicates how light photons physically accumulate on photographic film or camera CMOS sensors.

What causes chromatic aberration fringing around bokeh discs?

Chromatic aberration occurs because different wavelengths of light (red, green, blue) bend at slightly different refractive angles when passing through glass lens elements (optical dispersion). In Canvas, offsetting the red and blue channel rendering paths slightly reproduces this cinematic optical imperfection.

How can rack focus be animated smoothly between different UI sections?

By using linear interpolation (lerp) on the camera focus distance: `currentFocus += (targetFocus - currentFocus) * dampingFactor`. When the user scrolls past specific sections or hovers over cards, update `targetFocus` to the Z-depth of that section to smoothly pull the bokeh focal plane.

← Back to all blog guides Launch Generator Studio →