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!


\

Disclaimer: The articles reposted on this site are sourced from public platforms and are provided for informational purposes only. They do not necessarily reflect the views of MEXC. All rights remain with the original authors. If you believe any content infringes on third-party rights, please contact service@support.mexc.com for removal. MEXC makes no guarantees regarding the accuracy, completeness, or timeliness of the content and is not responsible for any actions taken based on the information provided. The content does not constitute financial, legal, or other professional advice, nor should it be considered a recommendation or endorsement by MEXC.
Share Insights

You May Also Like

Xiao Feng: Ethereum is still the core of applications and is difficult to replace due to its first-mover advantage and continuous optimization

Xiao Feng: Ethereum is still the core of applications and is difficult to replace due to its first-mover advantage and continuous optimization

PANews reported on October 22nd that at the ETHShanghai 2025 main forum, Xiao Feng, Vice Chairman and Executive Director of Wanxiang Holdings, Chairman of Wanxiang Blockchain, and Chairman and CEO of HashKey Group, stated that blockchains can be broadly divided into two categories. One, represented by Bitcoin, is primarily a currency issuance system that achieves high-speed calculations through simple mathematical formulas and prohibits complex external deployment, allowing for rapid global consensus, hence its esteemed status as "digital gold." The other, represented by Ethereum, is application-centric and has gradually developed along the lines of the original white paper, currently holding 60%-70% of the application market share. Xiao Feng noted that there is no need to attempt to replace Ethereum, as it has a first-mover advantage and is continuously improving. Other blockchain projects need to demonstrate that their strategic positioning differs from Ethereum and that they offer differentiated value, making the possibility of challenging Ethereum very low. Xiao Feng also emphasized that the development of DeFi cannot be ignored, but it needs to take into account KYC and anti-money laundering requirements, as its philosophy differs from traditional finance. Through zero-knowledge identity authentication (ZK ID), users can verify their identity as qualified investors using information such as certificates, proof, and work experience, allowing them to trade securely around the world, allowing decentralized finance to better serve the global financial system.
Share
2025/10/22 11:14
Share
Coinbase Buys Echo Platform in $375m Deal

Coinbase Buys Echo Platform in $375m Deal

Coinbase has announced that it is acquiring Echo, an investment platform that is built on blockchain, at approximately $375M. This marks Coinbase’s eighth acquisition of 2025 and twelfth overall. The deal highlights the exchange giant’s commitment to democratizing access to early-stage crypto investing while enhancing its Base ecosystem. Partnership to Full Ownership Coinbase Ventures was awarded the position of Group Lead on the platform in March 2025. The collaboration focused on extending funding opportunities for projects based on Base, Coinbase’s Layer-2 network. Coinbase Ventures invested in over 40 projects, including Aerodrome, Morpho, and Blackbird. Echo was launched in March 2024 by crypto thought leader Jordan Fish (known as “Cobie”) with the goal of democratizing early-stage blockchain financing. The platform allows accredited and qualified investors to construct web3 projects through transparent, on-chain transactions. This approach contrasts with traditional venture capital, where only wealthy investors obtain access to promising startups. The acquisition provides Coinbase with complete control over a platform that has facilitated fundraising for over 30 crypto projects, such as Ethena, Morph, Usual, and MegaETH. MegaETH completed two separates $10M raises through Echo in December 2024, with a round closing in just 56 seconds. Breaking Down Traditional Barriers in Crypto Funding The traditional venture capital approach in cryptocurrency has been chastised for providing exclusive access to privileged insiders who obtain early token allocations at significant discounts. These insiders often distribute their tokens to high-priced retail investors. Echo’s community-driven model reaffirms this trend since smart contracts are used to effectively manage funds. Shan Aggarwal, the Vice President of Corporate and Business Development for Coinbase, stated that on-chain investing is possible to engage accredited and qualified investors in a manner that it was previously not capable of doing. Jesse Pollak, the Head of Base and Coinbase Wallet, stated that it allows more dynamic capital base to founders. Through Web3, these collaborative efforts have been implemented in a similar way. The Coinbase-Echo merger is an example of strategic alliances that can increase the value of the customers and the developers. Empowering the Base Ecosystem and Industry Impact The purchase follows the Base network of Coinbase becoming the most successful Layer-2 solution of Ethereum in a range of significant aspects. With Echo’s integration, Coinbase will have the opportunity to distribute funds to Base builders, as well as provide community members with direct investment opportunities in network-shaping projects. The $375M price is based on Echo’s history of success and strategic significance of Coinbase in utilizing on-chain capital formation infrastructure. Echo has raised more than $100M within a year, which shows strong product-market presence and willingness to have advantageous opportunities to invest in cryptocurrencies. This transaction is at forefront of transparent blockchain-based fundraising, which overcomes information asymmetry and improves traditional venture financing. The deal also highlights how Coinbase plans to pursue an active M&A strategy in 2025, which indicates that it is the eighth deal of the year and shows that the company is optimistic about the future of crypto. Conclusion The acquisition of Echo by Coinbase of $375M signifies the breakthrough in fundraising of cryptocurrencies. The deal will merge Coinbase regulatory expertise and Base ecosystem with Echo’s democratized investing platform to create infrastructure that will transform early-stage crypto finance. The Base network is expanding, and it is focusing on transparent capital deployment techniques that are becoming essential for the long-term growth of the industry.
Share
2025/10/22 10:00
Share