The fractal is made by utilizing the numbers in the Mandelbrot Set, but because I'm lazy and wikipedia is awesome - feel free to read more about it there.

Without further ado:

Your browser does no support the <canvas> yet.

And for your pleasure:

``````function mandelbrot() {
canvas = document.getElementById("mandelbrot_canvas");
ctx = canvas.getContext("2d");

// read the width and height of the canvas
width = parseInt(canvas.getAttribute("width"));
height = parseInt(canvas.getAttribute("height"));

// create a new pixel array
imageData = ctx.createImageData(width, height);

// draw random dots
for (xc=0; xc<width; xc++) {
for (yc=0; yc<height; yc++) {
//convert screen coords to coords around 0
var zoom = 1;
var x0 = (-(width/2) + xc - (width/4))*zoom/(width/2);// co-ordinate of pixel
var y0 = (-(height/2) + yc)*zoom/(height/2);// co-ordinate of pixel

var x = 0; //temp coords
var y = 0;

var iteration = 0;          //current iteration
var max_iteration = 1000;   //max iteration
//calculate the mandelbrot set
while ( ((x*x) + (y*y) <= (2*2))  &&  (iteration < max_iteration) )
{
var xtemp = (x*x) - (y*y) + x0;
y = (2*x*y) + y0;
x = xtemp;
iteration++;
}
index = (xc + yc * imageData.width) * 4;
var val = 255;
imageData.data[index+3] = 0;
if ( iteration >= max_iteration ){ val = 0; imageData.data[index+3] = 0xff; }
imageData.data[index+0] = imageData.data[index+1] = imageData.data[index+2] = val;
}
}

// copy the image data back onto the canvas
ctx.putImageData(imageData, 0, 0); // at coords 0,0
}
```
```
blog comments powered by Disqus

21 October 2012