Skip to content

Instantly share code, notes, and snippets.

@juliengrenier
Created September 19, 2012 12:56
Show Gist options
  • Save juliengrenier/3749492 to your computer and use it in GitHub Desktop.
Save juliengrenier/3749492 to your computer and use it in GitHub Desktop.
javascript tree generator
function randomRange(lowerBound, upperBound){
return lowerBound + Math.random() * (upperBound-lowerBound);
}
function draw() {
var canvas = document.getElementById("canvas");
var c = canvas.getContext("2d");
function drawBranch(l, direction) {
c.save();
c.fillRect(-1, 0, 2, -l);
c.translate(0, -l);
if ( l > 5 ) {
drawBranch(l * randomRange(0.7, 0.9), -direction);
c.rotate(randRange(0.5, 0.6) * -direction);
drawBranch(l * randomRange(0.6, 0.8), direction);
if (Math.random() > 0.2){
drawBranch(l * randomRange(0.3, 0.5), -direction);
}
}else {
var r = Math.random();
if (r < 1.55){
c.fillStyle = "green";
}else if (r < 1.75){
c.fillStyle = "orange";
}else{
c.fillStyle = "red";
}
c.fillRect(-2, -2, 4, 4);
}
c.restore();
}
c.translate(200, 300);
drawBranch(50, 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment