Julia Set

Under Construction

How would you draw a Julia set on a computer?

p5.js Web Editor

Complex Numbers

Real Numbers

Imaginary Numbers

Complex Plane

Complex Numbers Review

Objects

Literal Notation

Properties

Objects Review

Julia Set

Quadratic Polynomials

Composition and Iteration

Escape Radius

let c, r;

function setup() {
  createCanvas(400, 400);
  noLoop();
  colorMode(HSB);

  c = { real: -0.4, imag: 0.6 };
  r = escapeRadius(c);
}

function draw() {
  for (let x = 0; x < width; x += 1) {
    for (let y = 0; y < height; y += 1) {
      let z = {
        real: 0.01 * (x - width/2),
        imag: 0.01 * (y - height/2)
      };
      let iteration = 0;
      const maxIteration = 255;
      while (mag(z.real, z.imag) < r && iteration < maxIteration) {
        z = f(z)
        iteration += 1;
      }
      
      if (iteration === maxIteration) {
        stroke(0);
      } else {
        stroke(255 - iteration, 255, 25*iteration);
      }
      
      point(x, y);
    }
  }
}

function add(z1, z2) {
  const real = z1.real + z2.real;
  const imag = z1.imag + z2.imag;
  
  return { real, imag };
}

function mult(z1, z2) {
  const real = z1.real * z2.real - z1.imag * z2.imag;
  const imag = z1.real * z2.imag + z1.imag * z2.real;
  
  return { real, imag };
}

function escapeRadius(c) {
  const cmag = mag(c.real, c.imag);
  const radius = 1.1 * (1 + sqrt(1 + 4 * cmag));
  
  return radius;
}

function f(z) {
  const zsquared = mult(z, z);
  const output = add(zsquared, c);

  return output;
}

Julia Set Review

Project Ideas

Animation Make the real and imag components of c vary with time using sin() and cos().

Coding Train Check out Daniel Shiffman’s tutorials on the Mandelbrot and Julia sets for even more project ideas.


This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.