Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 50 ยท Projects, Practice and Review

Project: A Fractal Explorer

Build a Mandelbrot and Julia set explorer in JavaScript: escape-time rendering, smooth coloring, cosine palettes, click-to-zoom and speed-ups, rendered live.

A fractal explorer is one of the most satisfying small graphics programs you can write. A dozen lines of arithmetic produce an image of unlimited detail, and a click zooms into a new world. In Bezier Surfaces and Fractals you met the Mandelbrot and Julia sets. In this project you turn them into a proper tool: smooth colors, selectable palettes, click-to-zoom, and the optimizations that make deep zooms practical.

You will also meet the honest limit of the technique. Zoom far enough and the picture turns into blocks, not because of a bug but because of how computers store numbers.

The escape-time algorithm

Take a complex number c and start from z = 0. Repeat z = z^2 + c. If |z| ever exceeds 2, the sequence runs off to infinity and c is not in the Mandelbrot set. If it stays bounded, c is in the set. The Julia set for a fixed c asks the same question for different starting points: start from z = pixel and iterate with the same constant c for every pixel.

Complex arithmetic is just two real numbers. With z = x + yi and c = a + bi:

TEXT
x' = x*x - y*y + a
y' = 2*x*y + b

We cannot iterate forever, so we stop after maxIter steps and call everything that has not escaped "inside" (painted black). The escape iteration count n becomes the color of every outside pixel.

flowchart TD
  A["For each pixel: map to a complex number"] --> B["Mandelbrot: c = pixel, z = 0<br/>Julia: z = pixel, c = constant"]
  B --> C["Repeat z = z^2 + c"]
  C --> D{"|z| above bailout?"}
  D -->|yes| E["Outside: color from iteration count"]
  D -->|no| F{"Iterations left?"}
  F -->|yes| C
  F -->|no| G["Inside: black"]

The same loop draws both sets; only the starting values differ.

From pixel to complex number

The view is described by a center (cx, cy) and a width in complex units. Pixel (px, py) maps to

TEXT
re = cx + (px / W - 0.5) * width
im = cy - (py / H - 0.5) * width * H / W

The minus in the imaginary part flips the y axis, as in Coordinate Systems. Zooming in by 2 around a clicked pixel means: move the center to that pixel's complex coordinates and halve the width. That is the entire navigation code.

Smooth coloring

If you color by the integer n, you get ugly bands. The fix is to estimate a fractional escape count. Use a large bailout radius (we use 256) and compute

TEXT
nu = n + 1 - log2( ln|z| )

where z is the value at escape. Because |z| grows doubly exponentially, this correction exactly smooths the step between bands, and the colors vary continuously.

Palettes from a formula

A palette maps the number t = nu * speed to a color that repeats cyclically. A compact, popular way is the cosine palette: color = A + B * cos(2*pi * (C * t + D)), evaluated per channel. Four three-component vectors define an entire palette; change D and the colors shift, change C and they cycle faster per channel. Our explorer offers a few of these plus a grayscale ramp. This is the same idea as the color maps in Gradients, Palettes and Dithering.

The explorer

Click the image to zoom in 2x at that point. Change the set, the palette and the iteration limit; more iterations reveal finer structure at deep zooms but cost time. For the Julia sets, the constant is fixed by the preset you choose.

A Mandelbrot and Julia explorer

Try this tour: pick the Mandelbrot set, then click the thin neck at about -0.75 + 0.1i repeatedly, raising the iteration slider when the colors turn black or flat. Zoom has a price: near the boundary points need many iterations before they escape, and some never do within your limit.

Speed and the limits of the double

The explorer is quick because of a few habits worth copying.

  • Do the algebra by hand. The loop above uses x and y as plain numbers and reuses x*x and y*y for both the update and the escape test. Creating a complex-number object per iteration would be many times slower in JavaScript because of memory allocation.
  • Compare squared magnitudes. Test x*x + y*y > R*R instead of taking a square root.
  • Skip what you can prove. Every point of the main cardioid and the period-2 bulb is inside the set. Two cheap formulas detect them and save the full maxIter loop for the biggest black areas, which is where the loop is longest.
  • Use symmetry. The Mandelbrot set is mirrored across the real axis. When the view is centered on the axis you can compute half the rows.
  • Work in chunks. A deep zoom may take seconds. Render a few rows at a time (or in a Web Worker) and keep the page responsive. The same rows are completely independent, so the problem is ideal for parallel hardware, and a GPU fragment shader computes all pixels at once.

The second example demonstrates the two ideas that need numbers to explain: how much the shortcut saves, and where doubles run out of precision.

JS Savings from the shortcut, and the precision wall

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A double has about 15 to 16 significant decimal digits. When the pixel spacing falls near 1e-16 times the size of the coordinates, neighbouring pixels map to the same number and the image turns blocky, whatever the iteration limit. Deeper explorers switch to higher-precision arithmetic or use perturbation theory, which computes one reference orbit in extended precision and approximates all other pixels as small differences from it.

Ideas for extending the explorer

  • Drag to pan and a mouse wheel to zoom smoothly.
  • Interactive Julia. Show the Julia set whose constant is the mouse position over the Mandelbrot set; the two images are tightly related.
  • Orbit trap and distance coloring. Color by how close the orbit comes to a point or line, for filigree patterns.
  • Progressive rendering. Compute a low-resolution preview first, then refine.
  • Other fractals. Change the formula to z^3 + c, the Burning Ship (abs on both parts before squaring) or the Newton fractal, which iterates a root-finding method and colors by the root reached.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What distinguishes the Julia set loop from the Mandelbrot loop?

    Both iterate z = z^2 + c. They differ only in which of the two values comes from the pixel.
  2. 2. Why use a large bailout radius such as 256 with the smooth-coloring formula?

    The smoothing formula assumes the orbit is already growing fast. A larger radius makes the estimate of the fractional iteration count accurate.
  3. 3. How does a click zoom in 2x at the clicked pixel?

    The view is defined by a center and a width. Updating those two values and rendering again is all that is needed.
  4. 4. What does the cardioid and bulb test do?

    Points in the main cardioid and the period-2 bulb never escape. Two cheap inequalities find them without running maxIter iterations.
  5. 5. Why does a very deep zoom turn into blocks even with a huge iteration limit?

    The limit is numeric precision, not iteration count. Arbitrary-precision arithmetic or perturbation methods go deeper.

Summary

  • The Mandelbrot and Julia sets share one loop, z = z^2 + c, and the pixel decides whether it provides c or the starting z.
  • A view is a center and a width; clicking recenters and halves the width.
  • Smooth coloring uses n + 1 - log2(ln|z|), and cosine palettes turn the result into colors.
  • Hand-expanded real arithmetic, squared magnitudes and the cardioid and bulb test make the loop fast.
  • Doubles run out of precision around 1e-15 zooms; deeper needs extended precision or perturbation.

To test your own skills, continue with Practice: Exercises with Solutions.