Home

Mandelbrot in WebGL

I remember once having written a version of the Mandelbrot set using the HTML5 <canvas> element, writing to the raw pixel buffer using javascript. It was nice, but very slow. I decided recently to take a dive into how WebGL works, by this simple project: write something that renders the Mandelbrot set (in a sufficiently pretty way) using WebGL.

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.