Kamel Ghabte · Course · Free

Fractals: Mandelbrot

Visualize the Mandelbrot set in p5.js.

The concept

The Mandelbrot set is defined by iterating z = z² + c in the complex plane. For each point c, if the sequence diverges quickly, the point is outside (colored by divergence speed). Otherwise it's in the set (black). The result is a fractal of infinite complexity at every scale.

The code

// Mandelbrot set
function setup() { createCanvas(400, 280); pixelDensity(1); noLoop(); }
function draw() {
  loadPixels();
  for (let px=0;px<width;px++) for (let py=0;py<height;py++) {
    let x0=map(px,0,width,-2.5,1), y0=map(py,0,height,-1.2,1.2);
    let x=0,y=0,i=0;
    while(x*x+y*y<4&&i<80){let t=x*x-y*y+x0;y=2*x*y+y0;x=t;i++;}
    let c=map(i,0,80,0,255); let idx=(py*width+px)*4;
    pixels[idx]=c*0.2;pixels[idx+1]=c*0.7;pixels[idx+2]=c*0.9;pixels[idx+3]=255;
  }
  updatePixels();
}

Going further

Explore other free courses on the Learn page, or book a call to discuss your project.

Want to go further?

Book a discovery call →