Fractals are never-ending patterns created by repeating mathematical equations. We’ll draw one of the best-known Fractals, using only Vanilla JS and the HTML5 Canvas API.Fractals are never-ending patterns created by repeating mathematical equations. We’ll draw one of the best-known Fractals, using only Vanilla JS and the HTML5 Canvas API.

Coding a Fractal Tree With JavaScript and HTML5

2025/10/11 03:00

\ Fractals, those enigmatic figures that are everywhere but can not be seen by the untrained eye. Today we’ll draw one of the best-known Fractals, using only Vanilla JS and the HTML5 Canvas API. Let’s code!

What You’ll Learn

  • What is a Fractal Tree?
  • Writing the Fractal Tree in Vanilla JS
  • Beyond the Fractal Tree

What is a Fractal Tree?

To define a Fractal Tree, first, we must know the definition of Fractal, of course.

Fractals are never-ending patterns created by repeating mathematical equations, which, on any scale, on any level of zoom, look roughly the same. In other words, a geometric object which’s basic structure, rough or fragmented, repeats itself in different scales.

So if we split a Fractal, we’ll see a reduced-size copy of the whole.

Benoit Mandelbrot, who coined the term Fractal in 1975, said:

\

\ Pretty clear, right?

Here are some examples:

Animated Von Koch Curve

\ Animated Sierpinski Carpet

Now, what is a Fractal Tree?

Imagine a branch, and branches coming out of it, and then two branches coming out of each branch, and so on… that’s what a Fractal Tree looks like.

Its form comes from the Sierpinski triangle (or Sierpinski gasket).

As you can see, one becomes the other when changing the angle between branches:

From Sierpinski Triangle to Fractal

Today, we’ll end up with a figure similar to the final form of that GIF.

Writing the Fractal Tree in Vanilla JS

First of all, here’s the final product (you can tweak it along the way):

Final Fractal Tree

Now let’s draw that, step by step.

First of all, we initialize our index.html file with a canvas of any reasonable dimensions and a script tag where all our JS code will be.

<!doctype html> <html lang="en">   <head>     <meta charset="UTF-8" />   </head>   <body>     <canvas id="my_canvas" width="1000" height="800"></canvas>     <script></script>   </body> </html> 

Then, we start writing our JavaScript.

We initialize our canvas element on JS, by accessing it through the myCanvas variable and creating the 2D rendering context with the ctx (context) variable.

<!doctype html> <html lang="en">   <head>     <meta charset="UTF-8" />   </head>   <body>     <canvas id="my_canvas" width="1000" height="800"></canvas>     <script>       var myCanvas = document.getElementById("my_canvas");       var ctx = myCanvas.getContext("2d");     </script>   </body> </html> 

So yeah, the getContext method adds properties and methods that allow you to draw, in this case, in 2D.

Now it’s time to think. How can we define the algorithm to draw a Fractal tree? Hm… 🤔

Let’s see, we know that the branches keep becoming smaller. And that each branch ends with two branches coming out of it, one to the left and one to the right.

In other words, when a branch is long enough, attach two smaller branches to it. Repeat.

It kinda sounds like we should use some recursive statement somewhere, isn’t it?

Back to the code, we now define our function fractalTree that should take at least four arguments: the X and Y coordinates where the branch starts, the length of its branch, and its angle.

Inside our function, we begin the drawing with the beginPath() method, and then save the state of the canvas with the save() method.

<!doctype html> <html lang="en">   <head>     <meta charset="UTF-8" />   </head>   <body>     <canvas id="my_canvas" width="1000" height="800"></canvas>     <script>       var myCanvas = document.getElementById("my_canvas");       var ctx = myCanvas.getContext("2d");       function draw(startX, startY, len, angle) {           ctx.beginPath();           ctx.save();       }     </script>   </body> </html> 

The beginPath method is often used when you start a new line or figure that has a fixed style, like the same color along the entire line, or the same width. The save method just saves the entire state of the canvas by pushing the current state onto a stack.

Now we’ll draw our Fractal Tree by drawing a line (branch), rotating the canvas, drawing the next branch, and so on. It goes like this (I’ll explain each method below the code sample):

<!doctype html> <html lang="en">   <head>     <meta charset="UTF-8" />   </head>   <body>     <canvas id="my_canvas" width="1000" height="800"></canvas>     <script>       var myCanvas = document.getElementById("my_canvas");       var ctx = myCanvas.getContext("2d");       function draw(startX, startY, len, angle) {           ctx.beginPath();           ctx.save();            ctx.translate(startX, startY);           ctx.rotate(angle * Math.PI/180);           ctx.moveTo(0, 0);           ctx.lineTo(0, -len);           ctx.stroke();            if(len < 10) {               ctx.restore();               return;           }            draw(0, -len, len*0.8, -15);           draw(0, -len, len*0.8, +15);            ctx.restore();       }       draw(400, 600, 120, 0)     </script>   </body> </html> 

So we first add three methods, translate, rotate, and moveTo, which “moves” the canvas, its origin, and our “pencil” so we can draw the branch in our desired angle. It’s like we are drawing a branch, then centering this branch (by moving the whole canvas), and then drawing a new branch from the end of our previous branch.

The last two methods before the if statement are lineTo and stroke; the first adds a straight line to the current path, and the second one renders it. You can think of it like this: lineTo gives the order, and stroke executes it.

Now we have an if statement that tells when to stop the recursion, when to stop drawing. The restore method, as stated in the MDN Docs, “restores the most recently saved canvas state by popping the top entry in the drawing state stack”.

After the if statement, we have the recursive call and another call to the restore method. And then a call to the function that we just finished.

Now run the code in your browser. You’ll see, finally, a Fractal Tree!

Fractal Tree First Iteration

Awesome, right? Now let’s make it even better.

We’ll add a new parameter to our draw function, branchWidth, to make our Fractal Tree more realistic.

<!doctype html> <html lang="en">   <head>     <meta charset="UTF-8" />   </head>   <body>     <canvas id="my_canvas" width="1000" height="800"></canvas>     <script>       var myCanvas = document.getElementById("my_canvas");       var ctx = myCanvas.getContext("2d");       function draw(startX, startY, len, angle, branchWidth) {           ctx.lineWidth = branchWidth;            ctx.beginPath();           ctx.save();            ctx.translate(startX, startY);           ctx.rotate(angle * Math.PI/180);           ctx.moveTo(0, 0);           ctx.lineTo(0, -len);           ctx.stroke();            if(len < 10) {               ctx.restore();               return;           }            draw(0, -len, len*0.8, angle-15, branchWidth*0.8);           draw(0, -len, len*0.8, angle+15, branchWidth*0.8);            ctx.restore();       }       draw(400, 600, 120, 0, 10)     </script>   </body> </html> 

So in every iteration, we are making each branch thinner. I’ve also changed the angle parameter in the recursive call to make a more “open” tree.

Now, let’s add some color! And shadows, why not.

<!doctype html> <html lang="en">   <head>     <meta charset="UTF-8" />   </head>   <body>     <canvas id="my_canvas" width="1000" height="800"></canvas>     <script>       var myCanvas = document.getElementById("my_canvas");       var ctx = myCanvas.getContext("2d");       function draw(startX, startY, len, angle, branchWidth) {           ctx.lineWidth = branchWidth;            ctx.beginPath();           ctx.save();            ctx.strokeStyle = "green";           ctx.fillStyle = "green";            ctx.translate(startX, startY);           ctx.rotate(angle * Math.PI/180);           ctx.moveTo(0, 0);           ctx.lineTo(0, -len);           ctx.stroke();            ctx.shadowBlur = 15;           ctx.shadowColor = "rgba(0,0,0,0.8)";            if(len < 10) {               ctx.restore();               return;           }            draw(0, -len, len*0.8, angle-15, branchWidth*0.8);           draw(0, -len, len*0.8, angle+15, branchWidth*0.8);            ctx.restore();       }       draw(400, 600, 120, 0, 10)     </script>   </body> </html> 

Both color methods are self-explanatory (strokeStyle and fillStyle). Also, the shadow ones, shadowBlur and shadowColor.

And that’s it! Save the file and open it with your browser to see the final product.

Now I encourage you to play with the code! Change the shadowColor, the fillStyle, make a shorter or longer Fractal Tree, change the angle, or try to add leaves, that should be challenging 😉

Beyond the Fractal Tree

As I showed you at the beginning of this post, there are different Fractals. Ain’t gonna be easy to make all those with the Canvas API, but it should be possible. I made some of those in the C programming language, and I’ve also played around with p5.js.

p5.js is an Open Source JavaScript library made by artists, for artists, based on the Processing language. You can draw or animate anything imaginable. If you are interested in making art with code, it’s a must. They have a great get-started page that you can check out here.


Well, that’s it for now! Thanks for reading, comment any questions, and see you in my next post!


\

Sorumluluk Reddi: Bu sitede yeniden yayınlanan makaleler, halka açık platformlardan alınmıştır ve yalnızca bilgilendirme amaçlıdır. MEXC'nin görüşlerini yansıtmayabilir. Tüm hakları telif sahiplerine aittir. Herhangi bir içeriğin üçüncü taraf haklarını ihlal ettiğini düşünüyorsanız, kaldırılması için lütfen service@support.mexc.com ile iletişime geçin. MEXC, içeriğin doğruluğu, eksiksizliği veya güncelliği konusunda hiçbir garanti vermez ve sağlanan bilgilere dayalı olarak alınan herhangi bir eylemden sorumlu değildir. İçerik, finansal, yasal veya diğer profesyonel tavsiye niteliğinde değildir ve MEXC tarafından bir tavsiye veya onay olarak değerlendirilmemelidir.

Ayrıca Şunları da Beğenebilirsiniz

American Bitcoin’s $5B Nasdaq Debut Puts Trump-Backed Miner in Crypto Spotlight

American Bitcoin’s $5B Nasdaq Debut Puts Trump-Backed Miner in Crypto Spotlight

The post American Bitcoin’s $5B Nasdaq Debut Puts Trump-Backed Miner in Crypto Spotlight appeared on BitcoinEthereumNews.com. Key Takeaways: American Bitcoin (ABTC) surged nearly 85% on its Nasdaq debut, briefly reaching a $5B valuation. The Trump family, alongside Hut 8 Mining, controls 98% of the newly merged crypto-mining entity. Eric Trump called Bitcoin “modern-day gold,” predicting it could reach $1 million per coin. American Bitcoin, a fast-rising crypto mining firm with strong political and institutional backing, has officially entered Wall Street. After merging with Gryphon Digital Mining, the company made its Nasdaq debut under the ticker ABTC, instantly drawing global attention to both its stock performance and its bold vision for Bitcoin’s future. Read More: Trump-Backed Crypto Firm Eyes Asia for Bold Bitcoin Expansion Nasdaq Debut: An Explosive First Day ABTC’s first day of trading proved as dramatic as expected. Shares surged almost 85% at the open, touching a peak of $14 before settling at lower levels by the close. That initial spike valued the company around $5 billion, positioning it as one of 2025’s most-watched listings. At the last session, ABTC has been trading at $7.28 per share, which is a small positive 2.97% per day. Although the price has decelerated since opening highs, analysts note that the company has been off to a strong start and early investor activity is a hard-to-find feat in a newly-launched crypto mining business. According to market watchers, the listing comes at a time of new momentum in the digital asset markets. With Bitcoin trading above $110,000 this quarter, American Bitcoin’s entry comes at a time when both institutional investors and retail traders are showing heightened interest in exposure to Bitcoin-linked equities. Ownership Structure: Trump Family and Hut 8 at the Helm Its management and ownership set up has increased the visibility of the company. The Trump family and the Canadian mining giant Hut 8 Mining jointly own 98 percent…
Paylaş
BitcoinEthereumNews2025/09/18 01:33
CEO Sandeep Nailwal Shared Highlights About RWA on Polygon

CEO Sandeep Nailwal Shared Highlights About RWA on Polygon

The post CEO Sandeep Nailwal Shared Highlights About RWA on Polygon appeared on BitcoinEthereumNews.com. Polygon CEO Sandeep Nailwal highlighted Polygon’s lead in global bonds, Spiko US T-Bill, and Spiko Euro T-Bill. Polygon published an X post to share that its roadmap to GigaGas was still scaling. Sentiments around POL price were last seen to be bearish. Polygon CEO Sandeep Nailwal shared key pointers from the Dune and RWA.xyz report. These pertain to highlights about RWA on Polygon. Simultaneously, Polygon underlined its roadmap towards GigaGas. Sentiments around POL price were last seen fumbling under bearish emotions. Polygon CEO Sandeep Nailwal on Polygon RWA CEO Sandeep Nailwal highlighted three key points from the Dune and RWA.xyz report. The Chief Executive of Polygon maintained that Polygon PoS was hosting RWA TVL worth $1.13 billion across 269 assets plus 2,900 holders. Nailwal confirmed from the report that RWA was happening on Polygon. The Dune and https://t.co/W6WSFlHoQF report on RWA is out and it shows that RWA is happening on Polygon. Here are a few highlights: – Leading in Global Bonds: Polygon holds 62% share of tokenized global bonds (driven by Spiko’s euro MMF and Cashlink euro issues) – Spiko U.S.… — Sandeep | CEO, Polygon Foundation (※,※) (@sandeepnailwal) September 17, 2025 The X post published by Polygon CEO Sandeep Nailwal underlined that the ecosystem was leading in global bonds by holding a 62% share of tokenized global bonds. He further highlighted that Polygon was leading with Spiko US T-Bill at approximately 29% share of TVL along with Ethereum, adding that the ecosystem had more than 50% share in the number of holders. Finally, Sandeep highlighted from the report that there was a strong adoption for Spiko Euro T-Bill with 38% share of TVL. He added that 68% of returns were on Polygon across all the chains. Polygon Roadmap to GigaGas In a different update from Polygon, the community…
Paylaş
BitcoinEthereumNews2025/09/18 01:10