Unleash the Power of Recursion: How to Generate a Sierpinski Triangle with p5.js

A Sierpinski triangle is a fractal pattern that is created by recursively dividing a triangle into smaller triangles. The pattern is formed by conn...

Get ready to create an amazing Sierpinski triangle and learn about the power of recursion! In this tutorial, we'll use p5.js and recursion to generate new points between three initial points and create a mesmerizing pattern. Whether you're a beginner or an experienced programmer, this tutorial will take you on a fun and exciting journey to discover the magic of recursion and create a beautiful Sierpinski triangle.

Table of Contents

Introduction

What is a Sierpinski triangle?

A Sierpinski triangle is a fractal pattern that is created by recursively dividing a triangle into smaller triangles. The pattern is formed by connecting the midpoints of the sides of the triangle, creating four smaller triangles. This process is repeated with each of the smaller triangles, creating an intricate and self-similar pattern.

What is recursion?

Recursion is a process in which a function calls itself repeatedly until a certain condition is met. It's a powerful tool that allows us to solve complex problems in a simpler and more elegant way. Recursion is often used in programming to solve problems that can be divided into smaller, similar problems, or to perform a task repeatedly with a varying set of inputs.

How will we create a Sierpinski triangle using recursion and p5.js?

In this tutorial, we'll use the p5.js library and the concept of recursion to generate a Sierpinski triangle. We'll start by setting up a canvas and initializing variables for the maximum number of points, the array of points, and the delay between each iteration. We'll then set up the draw() function, which will clear the canvas, draw the points, and generate new points using recursion. We'll also set up the generatePoints() function, which will choose a random point from the initial three points, calculate the midpoint between it and the last point in the array, add the new point to the array, and draw a line between the two points. Finally, we'll set up the midpoint() function, which will calculate the midpoint between two points and return it as an array. We'll then test the code to ensure that it is functioning correctly.

Setting up the canvas and initializing variables

Creating a canvas

To create a canvas, we'll use the createCanvas() function from p5.js. This function takes two arguments: the width and the height of the canvas. We'll set the width and height to 400 pixels each. We'll also set the background() function to white to give the canvas a clean look. Add the following code to the <script> tags in the <body> of the HTML file:

function setup() {
  createCanvas(400, 400);
  background(255);
}

Setting up the appearance of the points

Next, we'll set up the appearance of the points. We'll use the fill() function to set the color of the points to black, and the ellipse() function to draw the points as circles with a radius of 5 pixels. Add the following code to the draw() function:

fill(0);
ellipse(x, y, 5, 5);

Declaring variables

Next, we'll declare some variables that we'll use in the code. We'll declare a variable maxPoints to store the maximum number of points that we want to generate, and a variable ,delay, to store the delay between each iteration. We'll also declare an array points to store the points that we generate. Add the following code outside of any function:

let maxPoints = 1000;
let delay = 100;
let points = [];

Initializing the array of points

Finally, we'll initialize the array of points with the three initial points that we want to use to generate the Sierpinski triangle. We'll use the push() function to add the points to the array. Add the following code to the setup() function:

points.push([100, 100]);
points.push([300, 100]);
points.push([200, 300]);

Setting up the draw() function

Clearing the canvas

To clear the canvas between each iteration, we'll use the clear() function from p5.js. This function takes no arguments and simply clears the canvas. Add the following code to the beginning of the draw() function:

clear();

Drawing the points

Next, we'll loop through the array of points and draw each point on the canvas. We'll use the forEach() function to loop through the array, and the ellipse() function to draw the points. Add the following code to the draw() function:

points.forEach(point => {
  let [x, y] = point;
  fill(0);
  ellipse(x, y, 5, 5);
});

Stopping the animation

To stop the animation when the maximum number of points has been reached, we'll use an if statement to check if the length of the points array is equal to the maxPoints variable. If it is, we'll use the noLoop() function to stop the animation. Add the following code to the draw() function:

if (points.length === maxPoints) {
  noLoop();
}

Generating new points using recursion

To generate new points using recursion, we'll use the setTimeout() function to delay each iteration by the amount specified in the delay variable. We'll then call the generatePoints() function, which we'll set up in the next section. Add the following code to the draw() function:

setTimeout(() => {
  generatePoints();
}, delay);

Setting up the generatePoints() function

Choosing a random point

To choose a random point from the initial three points, we'll use the random() function from p5.js. This function takes a range as an argument and returns a random number within that range. We'll use it to choose a random index from the points array. Add the following code to the generatePoints() function:

let index = Math.floor(random(points.length));
let point = points[index];

Calculating the midpoint

Next, we'll calculate the midpoint between the chosen point and the last point in the array using the midpoint() function, which we'll set up in the next section. Add the following code to the generatePoints() function:

let lastPoint = points[points.length - 1];
let midpoint = midpoint(point, lastPoint);

Adding the new point to the array

To add the new point to the array, we'll use the push() function to add the midpoint to the end of the array. Add the following code to the generatePoints() function:

points.push(midpoint);

Drawing a line between the two points

To draw a line between the two points, we'll use the line() function from p5.js. This function takes four arguments: the x-coordinates and y-coordinates of the two points. Add the following code to the generatePoints() function:

line(point[0], point[1], midpoint[0], midpoint[1]);

Recursively generating more points

Finally, we'll use a recursive call to the generatePoints() function to generate more points. We'll add a base case to stop the recursion when the length of the points array is equal to the maxPoints variable. Add the following code to the generatePoints() function:

if (points.length < maxPoints) {
  generatePoints();
}

Setting up the midpoint() function

Calculating the midpoint between two points

To calculate the midpoint between two points, we'll simply take the average of their x-coordinates and y-coordinates. Add the following code to the midpoint() function:

let x = (point1[0] + point2[0]) / 2;
let y = (point1[1] + point2[1]) / 2;

Returning the midpoint

To return the midpoint, we'll use the return statement to return an array containing the x-coordinate and y-coordinate. Add the following code to the midpoint() function:

return [x, y];

Testing the code

To test the code, we'll need to include the p5.js library in the HTML file. To do this, we'll add the following <script> tag to the <head> of the HTML file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.min.js"></script>

Next, we'll create a sketch.js file and add the code for generating the Sierpinski triangle to it. We'll then include the sketch.js file in the HTML file using the following <script> tag:

<script src="sketch.js"></script>

Finally, we'll open the HTML file in a web browser to see the Sierpinski triangle being generated using recursion and p5.js. If the code is working correctly, you should see the points being drawn on the canvas, and the lines between the points forming a Sierpinski triangle. If you encounter any errors, make sure to check the console for any messages.

You can also adjust the parameters of the animation by changing the values of the delay, pointSize, and maxPoints variables. For example, you can increase the delay to slow down the animation, or increase the maxPoints to generate a more detailed Sierpinski triangle. Experiment with different values to see the effect on the animation.

Check out the demo in above video.

Conclusion

Recap of the key points

In this tutorial, we learned how to generate a Sierpinski triangle using recursion and p5.js. We covered the following key points:

  • What a Sierpinski triangle is and how it can be generated using recursion
  • How to set up a canvas and initialize variables in p5.js
  • How to generate new points using recursion and the setTimeout() function
  • How to calculate the midpoint between two points
  • How to add new points to an array and draw lines between them
  • How to test the code and adjust the animation parameters

Additional resources for learning more about recursion

If you'd like to learn more about recursion, here are some additional resources that you might find helpful:

If you want to see the full code and follow along with the tutorial, you can find it on my GitHub repository.

Hello! Myself Tejas Mahajan. I am an Android developer, Programmer, UI/UX designer, Student and Navodayan.