Introduction
In this article, we are going to understand working with tree fractals using HTML5. In this, we will see various randomized trees when the page is refreshed again and again in the browser.
Here we will use some JavaScript and some styles along with HTML code. Just go through the steps to see how to create this application.
Let's see how the TreeFractal application can be created. To do so use the following steps.
Step 1 : Open a HTML editor or Visual Studio.
Open File menu ->select new ->Choose Website then.


- Go to Solution Explorer
- Right-click on the Application name
- Select Add-->add new item
- Now in the window that opens, select an HTML page or a new Webform
- Rename it to Treefractal.aspx

- <style>
- body {
- margin: 0px;
- padding: 0px;
- font-family: Comic Sans MS;
- outline-color: Yellow;
- }
- #Bubble {
- border: 2px solid #9C9898;
- margin-top: 50px;
- margin-left: 60px;
- background-color: #00B2EE;
- box-shadow: 5px 5px 8px #222;
- }
- .title {
- text-align: center;
- font-family: Segoe UI Light, Arial, Helvetica;
- font-size: 2.2em;
- margin: 1em;
- }
- .info {
- text-align: center;
- font-family: Segoe UI Light, Arial, Helvetica;
- font-size: 1.2em;
- margin: 0.25em;
- }</style>
Step 3 : In this part we need to work on some JavaScript. To fully understanding how the JavaScript works, download the attached .rar file and run the TreeFractal application.
The whole JavaScript looks as in the following.
- <script>
- function drawBranches(startX, startY, trunkWidth, level)
- {
- canvas = document.getElementById("myCanvas");
- context = canvas.getContext("2d");
- if (level < 12) {
- var changeX = 100 / (level + 1);
- var changeY = 200 / (level + 1);
- var topRightX = startX + Math.random() * changeX;
- var topRightY = startY - Math.random() * changeY;
- var topLeftX = startX - Math.random() * changeX;
- var topLeftY = startY - Math.random() * changeY;
- // draw right branch
- context.beginPath();
- context.moveTo(startX + trunkWidth / 4, startY);
- context.quadraticCurveTo(startX + trunkWidth / 4, startY - trunkWidth, topRightX, topRightY);
- context.lineWidth = trunkWidth;
- context.lineCap = "round";
- context.stroke();
- // draw left branch
- context.beginPath();
- context.moveTo(startX - trunkWidth / 4, startY);
- context.quadraticCurveTo(startX - trunkWidth / 4, startY -
- trunkWidth, topLeftX, topLeftY);
- context.lineWidth = trunkWidth;
- context.lineCap = "round";
- context.stroke();
- drawBranches(topRightX, topRightY, trunkWidth * 0.7, level + 1);
- drawBranches(topLeftX, topLeftY, trunkWidth * 0.7, level + 1);
- }
- }
- window.onload = function ()
- {
- canvas = document.getElementById("myCanvas");
- context = canvas.getContext("2d");
- drawBranches(canvas.width / 2, canvas.height, 50, 0);
- };
- </script>



Join the conversation! Your thoughts help the community grow.