DEV Community

Cover image for Day 3 of #100DaysOfCode: JS Fractals in CodePen and Observable
Audrey Roy Greenfeld for Feldroy

Posted on

Day 3 of #100DaysOfCode: JS Fractals in CodePen and Observable

Yesterday I saw @lautarolobo 's tutorial on coding fractal trees in JS, and I knew I had to try it. Besides, it's Fractal Friday!

I opened up CodePen and was going to use HAML, then realized that the Pug HTML processor was available. Why not try Pug while I'm at it, right? My Pug code was nice and short:

h1 Fractal Tree
canvas#my_canvas(width="1000", height="800")
Enter fullscreen mode Exit fullscreen mode

I gave the canvas a nice light gray background so I could see the bounds:

#my_canvas { background-color: #efefef; }
Enter fullscreen mode Exit fullscreen mode

Then I defined the recursive draw() function as per the first tree version in @lautarolobo 's tutorial, where each execution:

  • Moves to startX, startY
  • Draws a line of length len, angle angle
  • Calls itself to draw left and right branches until len < 10

I brought the code over to Observable and hooked it up to sliders controlling the two values that were hardcoded: the ratio of new branch length to old, and the angle at which a new branch sprouts.

  • I got the slider code from Huy Nguyen's Fractal Tree notebook which is similar to this but more configurable.
  • I could have implemented this in CodePen but it would have been much more verbose than in Observable (I think)

Observable Notebook with JavaScript Fractal Tree

The above is just a screenshot because I don't think you can embed live running code on (unless I'm wrong?). Check out the interactive slider version:

Finally, I experimented with different left vs. right branch ratios back in CodePen and got some pretty results. Here's left branchPercent 0.5, right 0.8:

Fractal Tree, Leaning Right

Top comments (0)