This Gist was automatically created by Carbide, a free online programming environment.
Last active
August 21, 2016 21:03
-
-
Save antimatter15/cfe509da208a6b8ba039a451cdee6436 to your computer and use it in GitHub Desktop.
Fractal Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var canvas = document.createElement('canvas') ///**Visualize** any DOM element with the "HTML Element" Widget | |
canvas.width = 700 | |
canvas.height = 400 | |
canvas.style.width = '100%' | |
var ctx = canvas.getContext('2d'); | |
function drawTree(x1, y1, length, angle, n){ ///This is the recursive definition of the **drawTree** function. It takes four arguments:\\- x1: The starting X coordinate//- y1: The starting Y coordinate//- length: the length of the line segment to draw//- angle: The cumulative angle of the line segment//- n: The number of levels left to draw | |
var x2 = x1 + length * Math.cos(angle*Math.PI/180); | |
var y2 = y1 - length * Math.sin(angle*Math.PI/180); | |
ctx.beginPath(); | |
ctx.moveTo(x1, y1); | |
ctx.lineTo(x2, y2); | |
ctx.strokeStyle = n < 2 ? "green" : "brown"; | |
ctx.lineWidth = n - 1; | |
ctx.stroke(); | |
if(n == 0) return; ///**Stop drawing** the tree whenever there are no more branches left to draw | |
drawTree(x2, y2, length*0.75, angle+27, n-1); | |
drawTree(x2, y2, length*0.75, angle-57, n-1); ///**Manipulate **anything by dragging nice friendly sliders around | |
} | |
drawTree(350.5, 367, 100, 90, 11) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment