DEV Community

Cover image for Create an SVG Fractal Tree by Writing a Recursive Function - Easy JavaScript Tutorial
Piko
Piko

Posted on

Create an SVG Fractal Tree by Writing a Recursive Function - Easy JavaScript Tutorial

After a long hike searching for mushrooms and observing the trees around me with their beautiful patterns, I wondered if I could create a function to generate a tree in JavaScript. The next morning, I started researching and learned a bit about fractal mathematics and how it involves repeating the same pattern at different scales. This realization meant that I could probably create a recursive function to generate my tree.

I set out to create the function, and it turned out to be much simpler than I initially thought. Of course, this simplicity came after rewriting messy code multiple times. So now, I finally have a function that creates a cool fractal tree in less than 20 lines of code - it could be simplified to 10.

To render the tree, I used the SVG element, which I really enjoy working with. The function draws the first line (the base of the tree) and then recursively draws two lines at a time. The angles and lengths are calculated dynamically.

I learned a lot during this process, especially about how elegant and enjoyable using recursive functions can be. If you want to see how I did it or learn about using recursive functions to generate a pattern, I made a YouTube tutorial:

If you want to jump straight to the code:

Code Pen: https://codepen.io/Piko-the-solid/pen/RwvjNed
Github: https://github.com/PikoCanFly/fractal-tree

Top comments (0)