DEV Community

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

Posted on

3 1 2 1 1

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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay