HTML5 Game - Canvas Shape Tree

Drawing a tree

The following code creates a tree by drawing a trunk which forks into two branches.

It continues to draw two more branches that stem from the branches we just drew.

Demo

ResultView the demo in separate window

<html>
    <head>
        <script>
            function drawBranches(context, startX, startY, trunkWidth, level){
               if (level >2) {//from w  ww .jav a 2 s.c om
                  return;
               }
           
               let changeX = 100 / (level + 1);
               let changeY = 200 / (level + 1);
               
               let topRightX = startX + Math.random() * changeX;
               let topRightY = startY - Math.random() * changeY;
               
               let topLeftX = startX - Math.random() * changeX;
               let 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(context, topRightX, topRightY, trunkWidth * 0.7, level + 1);
               drawBranches(context, topLeftX, topLeftY, trunkWidth * 0.7, level + 1);
            }
            
            window.onload = function(){
                canvas = document.getElementById("myCanvas");
                context = canvas.getContext("2d");
                
                drawBranches(context, canvas.width / 2, canvas.height, 10, 0);
            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="500" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Note

The code used the recursive function that defines the mathematical nature of a tree.

Related Topics