Generating Julia Set fractals using math.js + HTML5
Fractals can be considered as a fusion of mathematics and art. By definition, fractals are mathematical sets that exhibit repeating patterns or self-similarity at every scale. They have a visual invariance regardless whether you zoom in or zoom out... and such a property provides much fascination that adds to its mystical beauty.
Fractals are generated by iterating through a complex equation, i.e. continually taking the output of the equation as the next input. The Julia Set in particular can simply be expressed as a quadratic recursive equation in the complex plane:
f(z) = z^2 + c
with c as a complex constant. Using math.js library to handle operations on the complex plane and HTML5 to create the canvas, beautiful fractals can be generated on a browser (that is not IE… sorry, I’m just biased against IE).
Here is the javascript function using math.js that computes the complex iterations:
function generate(x0, y0, c, maxIter) {
var i = 0;
var z0 = math.complex(c);
var z = math.complex(x0,y0);
while (math.abs(z) <= 2 && i < maxIter){
z = math.add(math.square(z), z0);
i++
}
return i;
}
The colors of the regions are then based on the proximity of the points, as determined by the function below:
function colorPix(pix, pos, i, iterations){
if (i > iterations) {
pix[pos] = 0;
pix[pos + 1] = 0;
pix[pos + 2] = 0;
} else {
var r = 3 * math.log(i) / math.log(iterations);
if (r < 1) {
pix[pos] = 0;
pix[pos + 1] = 0;
pix[pos + 2] = 255 * r;
}
else if ( r < 2 ) {
pix[pos] = 0;
pix[pos + 1] = 255 * (r - 1);
pix[pos + 2] = 0;
} else {
pix[pos] = 255 * (r-2);
pix[pos + 1] = 255;
pix[pos + 2] = 255;
}
}
pix[pos + 3] = 255;
}
The full codes are available here.
Investment Advisor | Educator
7yHoly moly, way above my pay grade but I'm a huge fan of Benoit Mandelbrot. I absolutely love his "Theory of Roughness" lecture.