Home

Mandelbrot in WebGL

I once wrote a program which displayed the Mandelbrot set using the HTML5 <canvas> element, writing to the raw pixel buffer using Javascript. It worked, but was very slow (despite my somewhat successful attempts to speed it up using parallelism in web workers). I’ve recently taken a dive into how WebGL works, by drawing the Mandelbrot set in WebGL rather than in Javascript.

The actual drawing the set is done in a single fragment shader, which you can find embedded in the html source for this page. The vertex shader does almost nothing, since the only geometry I have in the scene is a single square, so the job of the vertex shader is basically to interpolate coordinates and pass them along to the fragment shader.

The work done in the javascript file is about half nonsense to do with setting up WebGL, and then about half doing work with the coordinate system, which involves keeping track of where in the scene the viewer is, and takes in pan and scroll events and basically just spits out a single matrix to send along to the vertex shader, telling it where the camera is.

As you can see below, the result is pretty ok, and (at least on most computers I’ve tried) renders quite fast. However, it seems that WebGL only supports single-precision floats, so after zooming in not too far, the entire thing gets pixelated and stops resolving.