Skip to content

Instantly share code, notes, and snippets.

@konrup
Created July 22, 2017 13:17
Show Gist options
  • Save konrup/666462695f18d289e85ab289819eef61 to your computer and use it in GitHub Desktop.
Save konrup/666462695f18d289e85ab289819eef61 to your computer and use it in GitHub Desktop.
Draws a fractal tree on the canvas
function drawTree() {
var s = 5;
var n = 15;
var t = 30;
var cnvs = document.createElement("canvas");
var ctx = cnvs.getContext("2d");
document.body.appendChild(cnvs);
cnvs.height = 130 * s;
cnvs.width = 100 * s;
ctx.translate(0, cnvs.height);
ctx.scale(1, -1);
function tree(x, y, angle, len, n) {
if (n == 0) return;
ctx.beginPath();
var x2 = (x + Math.cos(angle) * len);
var y2 = (y + Math.sin(angle) * len);
ctx.lineWidth = (len / 10);
ctx.moveTo(x, y);
ctx.lineTo(x2, y2);
ctx.stroke();
if (n % 2 == 0) {
setTimeout(() => {
tree(x2, y2, angle - (10 * Math.PI / 180), len * 0.8, n - 1);
}, t);
setTimeout(() => {
tree(x2, y2, angle + (22 * Math.PI / 180), len * 0.6, n - 1);
}, t);
return;
}
if (n % 3 == 0) {
setTimeout(() => {
tree(x2, y2, angle + (15 * Math.PI / 180), len * 0.9, n - 1);
}, t);
setTimeout(() => {
tree(x2, y2, angle - (15 * Math.PI / 180), len * 0.6, n - 1);
}, t);
return;
} else {
setTimeout(() => {
tree(x2, y2, angle + (5 * Math.PI / 180), len * 0.9, n - 1);
}, t);
setTimeout(() => {
tree(x2, y2, angle - (15 * Math.PI / 180), len * 0.8, n - 1);
}, t);
}
}
tree(50 * s, 0, Math.PI / 2, 20 * s, n);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment