Trees created with God's math

God who created trees used a 3D canvas in addition to filling them with randomness and great complexity, but probably on the algorithm that basically could be minimal as follows.

God who created trees used a 3D canvas in addition to filling them with randomness and great complexity, but probably on the algorithm that basically could be minimal as follows.

Step 1: if a branch is long enough, attach two branches to it: one on the left, and one on the right. Both the new branches should be slightly shorter than the main branch.
Step 2: repeat step 1 for both new branches

Step 1: If a branch is long enough, attach two branches to it: one on the left, and one on the right. Both the new branches should be slightly shorter than their parent branch. Step 2: Repeat Step 1 for both the new branches

Here is the result of the video….

Let's try to understand how the concept of recursion works to draw the tree. Watch the video and rebuild the code that I execute.

 function draw(startX, startY, len, angle,branchWidth) { ctx.beginPath(); ctx.save(); ctx.translate(startX, startY); ctx.rotate(angle * Math.PI/180); ctx.moveTo(0, 0) ctx.strokeStyle = "darkgreen"; ctx.fillStyle = "green"; ctx.lineWidth = branchWidth; ctx.lineTo(0, -len); ctx.stroke(); if(len <7) { ctx.beginPath(); ctx.arc(0, -len, 5, 0, Math.PI/2); ctx.fill(); ctx.restore(); return; } draw(0, -len, len*0.8, angle-10,branchWidth*0.8); draw(0, -len, len*0.8,angle+10,branchWidth*0.8); ctx.restore() }

If you paid attention, the draw function calls itself many times and each time its parameters change. Recursion is the technique used to draw the tree.

Recursion means simply calling a function within its own definition, or in other words, a function is defined recursively when its definition includes a reference (call) to itself. With each call, the "depth" of processing increases until the goal is reached, at which point the function returns.

Many programming languages offer the possibility to define recursive functions or procedures; JavaScript is naturally one of these. Let's make an example just to clarify our ideas, let's see a trivial function (not recursive) for calculating the sum of two numbers:

12345 function sum(a,b){  return document.write(a + b);} 

Let's see the same example through a recursive function:

12345 function sum(a,b) {  return b > 0 ? sum(a + 1, b – 1) : document.write(a);}