Mandelbrot set using a HTML5 canvas and a JavaScript object
Mandelbrot data
r min:
r max:
i min:
i max:
Colour options
Instructions
Click the left-hand mouse button on the graphic to zoom in. Hold down either shift, ctrl or alt when clicking to zoom out. You can also zoom out by setting the zoom value to less than 1.0.
Move first two sliders to change the amount of zoom per click and also the maximum number of iterations carried out for each pixel. A larger number of iterations may be required as you zoom in to the fractal.
The next three sliders control the overall colour of the fractal. Moving these will immediately change the colour of the fractal.
About
The Mandelbrot set is an example of
a fractal. It is calculated by
taking a complex number, c,
and iterating it using the expression
zn+1 = zn2 + c
, where
z0 is zero. For each possible value of c the result of the iteration
either remains small no matter how many iterations are carried out, or becomes large. The result is
considered large if the magnitude
of z exceeds a value of 4.
Each pixel in the image represents a particular complex number. The colour of each pixel is determined by how many iterations it has undergone. Only the pixels with a magnitude below 4 continue to be iterated. Here the fractal is redrawn after each iteration, and the JavaScript has been written by defining a Mandelbrot object with associated properties and methods. It seems that this is faster than the functional or procedural methods I used to begin with.
Code snippets
I found it a bit tricky to work out how to update the canvas
after each iteration. To begin with I put the iteration and draw commands inside a for
loop, but
this only updated the canvas at the end of the loop. The solution was to use the
setInterval
command. The
function specified by this command is repeatidly run until the
clearInterval
command
is called. The canvas can be successfully updated within the function that is called. The setInterval
command is used on line 4 in the startCalculating
function below.
In this case it is the function progress
(line 7) that is called by the setInterval
command. The progress
function iterates the fractal and draws it on the canvas until the maximum
number of iterations has been reached. At this point the progress
function runs the
clearInterval
command to cancel the calling of progress
(line 11).
function startCalculating() { updateRanges(); updateColours(); calculating = setInterval(progress, 0); } function progress() { if (mandelbrot.numIterations <= mandelbrot.maxIterations) { mandelbrot.iterate(); mandelbrot.draw(); } else clearInterval(calculating); }