Skip to content

Instantly share code, notes, and snippets.

@0scarB
Created December 28, 2018 13:30
Show Gist options
  • Save 0scarB/7a08c188d57e3bf3d5c164f7a1c9c32e to your computer and use it in GitHub Desktop.
Save 0scarB/7a08c188d57e3bf3d5c164f7a1c9c32e to your computer and use it in GitHub Desktop.
paper.js sketch that generates trees with branches of varying length.
var width = view.size.width;
var height = view.size.height;
var averageLengthFac = 0.7;
var angleInc = Math.PI/4;
var iterations = 12;
function drawLine(x1, y1, x2, y2, color) {
var line = new Path(new Point(x1, y1));
line.strokeColor = color;
line.add(new Point(x2, y2));
}
function getNextBranchX(branch) {
var x = branch[0];
var length = branch[2];
var angle = branch[3];
return x + Math.cos(angle)*length;
}
function getNextBranchY(branch) {
var y = branch[1];
var length = branch[2];
var angle = branch[3];
return y + Math.sin(angle)*length;
}
function getBranchColor(branch) {
var length = branch[2];
var angle = branch[3];
return new Color(angle/(2*Math.PI), 1 - angle/(2*Math.PI), 1 - length/startLength);
}
function drawBranch(branch) {
var x = branch[0];
var y = branch[1];
drawLine(
x, y,
getNextBranchX(branch),
getNextBranchY(branch),
getBranchColor(branch)
);
}
function drawBranches(branches) {
for (var i = 0; i < branches.length; i++) {
drawBranch(branches[i]);
}
}
function getRandomStandardNormalDistribution() {
var x = 2 * Math.random() - 1;
if (x < 0) {
return -1/(Math.sqrt(2)*Math.PI)*Math.pow(
Math.E, -0.5*Math.pow(x, 2)
);
}
return 1/(Math.sqrt(2)*Math.PI)*Math.pow(
Math.E, -0.5*Math.pow(x, 2)
);
}
function getNextBranch(branch, nextAngle) {
var nextX = getNextBranchX(branch);
var nextY = getNextBranchY(branch);
var nextLength = branch[2]*(1 + getRandomStandardNormalDistribution())*averageLengthFac;
return [nextX, nextY, nextLength, nextAngle];
}
var startLength = height/8;
var groundY = 3*height/4;
var branches = [[width/2, groundY, startLength, -Math.PI/2]];
var background = new Path.Rectangle(view.bounds);
background.fillColor = 'black';
var ground = new Path.Rectangle(
new Point(0, groundY),
new Size(width, height - groundY)
);
ground.fillColor = new Color(0, 0.5, 0.5);
for (var i = 0; i < iterations; i++) {
drawBranches(branches);
if (i != iterations - 1) {
var nextBranches = [];
for (var j = 0; j < branches.length; j++) {
var branch = branches[j];
var angle = branch[3];
nextBranches.push(getNextBranch(branch, angle + angleInc));
nextBranches.push(getNextBranch(branch, angle - angleInc));
}
branches = nextBranches;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment