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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

👋 Kindness is contagious

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

Okay