canvas = document.getElementById("canvas"); context = canvas.getContext("2d"); width = canvas.width = window.innerWidth; height = canvas.height = window.innerHeight; var p0 = { x: width /2, y:height }, p1 = { x: width /2, y:50 }, branchAngleA = Math.PI / 5, branchAngleB = Math.PI / 5, trunkRatio = randomRange(0.37,0.4); truckchiant = 0.45; colors = [ '#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5', '#2196f3', '#03a9f4', '#00bcd4', '#009688', '#4CAF50', '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800', '#FF5722', '#795548' ]; finalcolor = colors[Math.floor(Math.random() * colors.length)]; function tree(p0,p1, limit){ var dx = p1.x - p0.x, dy = p1.y - p0.y, dist = Math.sqrt(dx * dx + dy * dy), angle = Math.atan2(dy,dx), branchLength = dist * (1- trunkRatio), pA = { x:p0.x + dx * trunkRatio, y:p0.y + dy * trunkRatio }, pB = { x:pA.x + Math.cos(angle + branchAngleA) * branchLength, y:pA.y + Math.sin(angle + branchAngleA) * branchLength, }, pC = { x:pA.x + Math.cos(angle - branchAngleB) * branchLength, y:pA.y + Math.sin(angle - branchAngleB) * branchLength, }; context.beginPath(); context.moveTo(p0.x, p0.y); context.lineTo(pA.x, pA.y); context.stroke(); if(limit > 0){ tree(pA, pC, limit -1); tree(pA, pB, limit -1); } else{ context.beginPath(); context.moveTo(pB.x, pB.y); context.lineTo(pA.x, pA.y); context.lineTo(pC.x, pC.y); context.strokeStyle="grey"; context.lineWidth = 2; context.lineCap = 'round'; context.stroke(); context.closePath(); context.beginPath(); context.arc(pB.x,pB.y,10, 0, Math.PI * 2); context.fillStyle=finalcolor; context.fill(); context.closePath(); context.beginPath(); context.arc(pC.x,pC.y,10, 0, Math.PI * 2); context.fill(); context.closePath(); } angle += 0.3; branchAngleA = 1 + Math.cos(truckchiant) * 0.35; branchAngleB = 1 + Math.sin(truckchiant) * 0.1; //branchAngleB += randomRange(-0.02,0.02); truckchiant += 0.2; } function update(){ context.clearRect(0,0,width,height); tree(p0,p1,5); requestAnimationFrame(update); } update(); function randomRange(min, max){ return min + Math.random() * (max - min ); } function randomInt(min, max){ return Math.floor(min + Math.random()* (max - min + 1)); }