Cantor’s Snowflake

The Koch snowflake is a famous fractal.

The Koch Snowflake fractal

So is the Cantor set.

The Cantor set

Less famous, maybe, is Cantor dust, a version of the Cantor set made with squares instead of lines, which apparently earned it a much cooler name.

But as far as I know, we have no Cantor snowflake.

Since it’s Christmas, and since, in the odd quiet moments between holiday noise, Daniel Shiffman’s Nature of Code has been keeping me company, I wondered if we could make a Cantor snowflake.

Here’s what I came up with.

cantor-snowflake

As a bonus, it contains the Koch snowflake inside of it! I didn’t expect that.

I also rendered a Cantor snowflake PDF, which has a couple extra generations. It could make a nice bookmark.

Here’s the sourcecode, which is also running on openprocessing:

void setup() {
  size(1450, 300);

  background(255);
  noStroke();
  fill(0);

  cantorSnowflake(0, height/2, 140, 280);
}

void cantorSnowflake(float x, float y, float length, float sideStep) {
  if (length < 0.1) return;

  pushMatrix();

  hexagon(x, y, length);

  translate(sideStep, 0);

  for (int i = 0; i < 6; i++) {
    PVector point = vector(i * THIRD_PI, length * 2 / 3);
    cantorSnowflake(point.x, point.y, length / 3, sideStep);
  }

  popMatrix();
}

void hexagon(float centerX, float centerY, float length) {
  translate(centerX, centerY);

  beginShape();
  for (int i = 0; i < 6; i++) {
    hexPoint(vector(i * THIRD_PI, length));
  }
  endShape(CLOSE);
}

void hexPoint(PVector v) {
  vertex(v.x, v.y);
}

PVector vector(float rads, float length) {
  return new PVector(cos(rads) * length, sin(rads) * length);
}

Happy Christmas!