An Introduction To The Chaos Game Algorithm In Javascript

What is the Chaos Game algorithm?

The Chaos Game is a method used to create fractals, notably Sierpinski triangle and Barnsley fern, using a simple iterative process. It leverages the principles of randomness and the plot points are constantly changing following a fixed set of rules.

How Does it Work?

The algorithm iteratively plots points that are halfway between a randomly-selected point from a pre-defined set of points and the previous point. This seemingly simple process results in the formation of a complex structure. Let's look at the process of creating a Sierpinski triangle using the Chaos Game Algorithm.

Implementing the Chaos Game Algorithm in JavaScript

The following JavaScript code creates a Sierpinski Triangle using the Chaos Game algorithm. For ease of visualization, this algorithm is implemented in JavaScript to be run in the browser context.

This JavaScript code leverages the p5.js library for ease of rendering.

const points = []; let current; function setup() { createCanvas(400, 400); points.push(createVector(width / 2, height / 2)); points.push(createVector(width / 2, height)); points.push(createVector(width, height / 2)); current = points[0]; } function draw() { background(0); stroke(255); strokeWeight(8); for (let p of points) { point(p.x, p.y); } strokeWeight(2); const next = random(points); current = p5.Vector.lerp(current, next, 0.5); point(current.x, current.y); }

This code first defines three points forming an equilateral triangle, then iteratively selects one of those three points and plots a new point halfway between the current point and the selected point. As the algorithm proceeds, the Sierpinski triangle emerges.

Conclusion

The Chaos Game algorithm provides a great example of how simple rules can lead to complex, often beautiful, phenomena. Implementing this algorithm in JavaScript forms a bridge between the mathematical underpinnings of fractal geometry and the practicalities of web-based visualization techniques.