Skip to content

Instantly share code, notes, and snippets.

@antimatter15
Last active August 21, 2016 21:03
Show Gist options
  • Save antimatter15/cfe509da208a6b8ba039a451cdee6436 to your computer and use it in GitHub Desktop.
Save antimatter15/cfe509da208a6b8ba039a451cdee6436 to your computer and use it in GitHub Desktop.
Fractal Tree
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