Fractal animation in pure JavaScript

Fractal animation

1. The fractal

We’ll use the Julia fractal. If you’re not interested in the mathematical details, feel free to skip the gray section below. All you need to know is:

  • it’s a great Javascript exercise
  • Julia fractals are mathematical images generated by iterating the calculation in rows 13-22 as long as the condition in row 24 is fulfilled. Then we plot the color corresponding to the value of i (=number of iterations).

For a fixed point c (its coordinates [c real and c imaginary] are defined in lines 4-5: experiment with different values between -2 and 2) in the complex plane, we’ll iterate the formula:

(lines 19-21) until the number of iterations reaches 255 or the result is higher than 4 (line 24). We could use a higher limit of iterations to get a more detailed image, but 255 is the highest value that HTML allows to assign to an RGB component. A result of 4 or more means that for complex coordinates that are currently being calculated the orbit escapes to infinity - this is what actually gives Julia its amazing shape.

We’ll plot the color corresponding to the number of iterations (lines 26-30). Lines 9-14 convert the the screen coordinates into complex coordinates.

Each point in the Mandelbrot set corresponds to a Julia set.

When it comes to animation, you can zoom into the Mandelbrot set, but Julia is more interesting because its shape is different for different c points.

2. Animation

With only a couple of additional lines (see the comments in the code), we can bring the fractal to life. All we’re doing is changing the c point with each animation frame and redrawing the fractal. By using the sin and cos functions, we’re moving it around on the complex plane, so that it ends up where it started. Experiment with the formulas in lines 37 and 38! We’ll also reduce the number of maximum iterations to 25 to allow even slower machines enough time for the calculations in each frame.

3. The colors

In the final step, we can replace the grayscale with a colorful pallette. The modified lines of code are commented below.

So far, we set the number of iterations for a given point as the Red, Green and Blue components of its color. This time we’ll create an array of 24 colors in 3 ranges, 8 colors in each. In each of the ranges, one of the RGB components will gradually increase from 0 to 255 (minimum and maximum values allowed by HTML), while the other two components are constant for each of the ranges.

#javascript

Fractal animation in pure JavaScript
50.85 GEEK