GreyHope Projects Demos Tutorials

Mandelbrot Visualisation

Back Next

2. JavaScript Canvas

On this page we will create a simple Mandelbrot Set using the JavaScript Canvas. This method is not the fastest, but it can zoom in a very long way.

To make the Mandelbrot Set with maximum detail, we need to treat each pixel as an individual square. We will use the fillRect function to fill each pixel in a different colour. Because JavaScript can't individually fill in every pixel of the screen at once, we need to do it slowly. That is why we will draw the set one column at a time.

The source code below draws the Mandelbrot Set starting at the left of the screen. It will then render each column until it gets to the right of the screen. As it moves along, each pixel is filled in a different colour based on its position on the set.

In the code above, the loop function contains exactly the same Mandelbrot algorithm that we discussed on the previous page. Feel free to change the PRECISION and ZOOM values. The x value refers to the column being drawn. At the end of every loop, the x value increases for the next column.

In the next example, we will let the user zoom in by clicking with the mouse. This means we also need a value to record our position on the set. Every time the user clicks, the x value will reset to 0 and the columns will be drawn from the left of the screen again.

To add colour, we will introduce a simple algorithm. We will use the % operator to find the remainder of index divided by 50. This means that the colours will form a pattern instead of getting brighter as you get nearer to the centre.

As you become engulfed by the endless sea of paterns, you will find that there is a limit. This is because JavaScript runs out of decimal places. Although this is very frustrating, there are some ways of getting the program to zoom in forever. This is achieved by using JavaScript BigInt which is a whole number that can go to any size. In the next tutorial, we will make a program that can zoom forever.

Back Next