mario::konrad
programming / C++ / sailing / nerd stuff
Mandelbrot Set
© 2013-03-21 / Mario Konrad

This page shows how to render a mandelbrot. It requires HTML5 Canvas and JavaScript.

Calculation

The mandelbrot set is calculated iteratively:

zn+1=zn2+cz_{n+1} = z_n^2 + c with z,cz, c in \mathbb{C}

Using cc as the starting point on the image, ranging from cmin=22ic_min = -2 - 2i to 2+2i2 + 2i.

Initial value: z=0+0iz = 0 + 0i

Maximum iterations: 2020

Demo

HTML5 Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
function draw_canvas_mandelbrot()
{
    var canvas = document.getElementById("embed-mandelbrot");
    var context = canvas.getContext('2d');
    var output = context.createImageData(canvas.width, canvas.height);
    var data = output.data;

    var re_min = -2.0;
    var re_max =  2.0;
    var im_min = -2.0;
    var im_max =  2.0;

    var max_iter = 20;

    for (var y = 0; y < output.height; ++y) {
        for (var x = 0; x < output.width; ++x) {
            var c_re = re_min + (re_max - re_min) / output.width * x;
            var c_im = im_min + (im_max - im_min) / output.height * y;
            var i = 0;
            var z_re = 0.0;
            var z_im = 0.0;
            for (; (i < max_iter) && (Math.sqrt(z_re * z_re + z_im * z_im) < 2.0); ++i) {
                z1_re = z_re * z_re - z_im * z_im + c_re;
                z1_im = 2.0 * z_re * z_im + c_im;
                z_re = z1_re;
                z_im = z1_im;
            }
            if (i >= max_iter) {
                data[(y*output.width + x)*4 + 0] = 0; // red
                data[(y*output.width + x)*4 + 1] = 0; // green
                data[(y*output.width + x)*4 + 2] = 0; // blue
                data[(y*output.width + x)*4 + 3] = 255; // alpha
            } else {
                data[(y*output.width + x)*4 + 0] = (255 * i) / max_iter; // red
                data[(y*output.width + x)*4 + 1] = (255 * i) / max_iter; // green
                data[(y*output.width + x)*4 + 2] = (255 * i) / max_iter; // blue
                data[(y*output.width + x)*4 + 3] = 255; // alpha
            }
        }
    }
    context.putImageData(output, 0, 0);
}

Mandelbrot Demo Applet

Source of the demo applet, use it at your own risk for whatever purpose you like.