# Learn p5.js by Making Fractals

## Educational drawing with math

Feb 13 · 5 min read

Even when I really want to learn a new programming language, framework, or tool, the process of getting started with it can feel like a chore. But it helps when the reward is high, and it helps even more if you can see the reward quickly.

This was my experience learning to make fractals in p5.js. With less than 40 lines of JavaScript code, you can make your own adjustable and customizable fractal tree as well.

I recommend watching Coding Train’s video on making fractal trees as well.

The only resource you’ll need to get started is the p5 library from the p5 website. The “p5.js complete” link gives you the library in a file named `p5.js`, which you can reference in another JavaScript file by including it in the head of your HTML file:

`<script src='./p5.js'></script><script src='./index.js></script>`

To instruct p5 to draw an image like the one at the top of this article, we need to break down the parts of what we’re trying to build and ask…

# What Is a Fractal?

Even if we’ve seen them many times before, the Oxford definition helps clarify:

“A curve or geometric figure, each part of which has the same statistical character as the whole.”

Before getting into the specifics, we might already imagine that whatever commands we write can repeat, maybe with some minor modification or progressive miniaturization, to continue rendering more and more smaller parts that have “the same statistical character” as their parent part.

# What Role Does p5 Play in This?

P5 does all the drawing for us.

We give just a few p5 instructions, and if we write them in such a way that the parameters of the instructions recursively (self-referentially) change themselves, we can have p5 execute a high number of operations while only writing a few instructions.

# Time to Get Drawing

If we are going to draw one of the most simple fractal forms, a tree with branches upon branches upon branches, we can start by drawing the first branch. But first, let’s set up our `index.js` file:

`function setup() {    createCanvas(800, 600)}`

We can write this on the first line. As the name implies, it creates our canvas.

Next:

`function draw() {    background(0)}`

`Setup()` and `draw()` are the first two functions that appear in every p5 file.

The next important function is `translate()`. The instructions we give to translate are x and y-coordinates on the screen, indicating the direction and distance the virtual brush should move to.

It’s important to keep track of the brush position since subsequent movements build on the movements made before. Within the draw function, we can refer to the width and height of the canvas to find the bottom like this:

`translate(width / 2, height)`

Now that we’re in position, we can draw a line with the `line()` function with the help of the `stroke()` function, which defines the color of our line:

`stroke(50, 50, 250)line(0,0,0, -150)`

All this together gives us a single line at the bottom of our canvas. If what we’ve drawn is our first branch and we want to draw further branches, let’s separate that branch into its own function and call it in our draw function.

Since we want to alter the length of the branch, the function can take in an argument of its length. Altogether, our code now looks like this:

To draw the next line, we need to start drawing from the end of the last line at a new angle. The angle is defined in relation to pi so we can add to our draw function like this:

Note the second time we’re translating. That takes us to the top of the branch. From there, we rotate our orientation by 45 degrees and draw a new branch that’s 3/4 the length of the last.

The natural thing to do next is draw our next branch which starts at the same place the last one did.

We could translate back there but then, when we make more and more branches, we’d have to translate up and down each fork which would become very hard to scale. This is why the next p5 tool is so useful.

## pop() and push()

These functions allow us to draw on our canvas then reset back to our previous position before drawing the next element.

The next time we’ll rotate the opposite angle and draw the same branch in that direction. The draw function now looks like this:

This gets us two branches. We’re well on our way! But to repeat this function, we still need to translate up the next branch then back down and back up the next way to draw further branches.

This still is very repetitive to execute without the power of…

## Recursion

Recursion will help us execute all our subsequent operations without writing each one out. Recursion is pretty powerful — powerful enough it could break your code by trying to run forever if you don’t give it a breakpoint.

I chose a breakpoint when the length of the branch reaches 1. This took my browser several seconds to run. You may want to set the minimum length to 3 or 5 or higher depending on the speed of your computer.

By moving the `push`, `pop`, `rotate`, and `branch` functions inside our branch function, our code now looks like this:

Which finally renders our first fractal:

# What’s Next?

If you’ve been running this code yourself, you may already have some ideas of how to experiment and customize. You can change the angle of rotation, length of the branch, add more branches, change the color, or modify the function much more drastically.

Sometimes, you may need to lower the minimum length established in the `if` statement if it takes too long to render.

Below is a modified version of the code above with the addition of a slider that allows the user to change the angle live in the browser.

Have fun making this project your own. P5 is a powerful tool and with a little knowledge of the common functionalities and their behaviors, you’re already well on your way.

To run this code, you can clone it from my GitHub repo.

Written by