xxxxxxxxxx
function setup() {
createCanvas(600, 600);
noLoop(); //the tree is drawn only once
}
function draw() {
background(220); //set background color
//randomize tree properties
let trunkHeight = random(100, 200);
let trunkWidth = random(20, 40);
let branchAngle = random(PI / 6, PI / 3);
let leafSize = random(10, 20);
let leafColor = color(random(50, 200), random(100, 255), random(50, 200));
//draw trunk
stroke(100, 50, 0);
strokeWeight(trunkWidth);
line(width / 2, height, width / 2, height - trunkHeight);
//draw branches
strokeWeight(2);
drawBranches(width / 2, height - trunkHeight, trunkHeight * 0.6, -PI / 2, branchAngle, 3, leafSize, leafColor);
}
function drawBranches(x, y, length, angle, branchAngle, depth, leafSize, leafColor) {
if (depth == 0) {
//draw a leaf at the end of branches
fill(leafColor);
noStroke();
ellipse(x, y, leafSize, leafSize);
return;
}
//calculate branch end points
let x1 = x + length * cos(angle - branchAngle);
let y1 = y + length * sin(angle - branchAngle);
let x2 = x + length * cos(angle + branchAngle);
let y2 = y + length * sin(angle + branchAngle);
//draw branches
stroke(100, 50, 0);
line(x, y, x1, y1);
line(x, y, x2, y2);
//recursively draw smaller branches
drawBranches(x1, y1, length * 0.7, angle - branchAngle, branchAngle, depth - 1, leafSize, leafColor);
drawBranches(x2, y2, length * 0.7, angle + branchAngle, branchAngle, depth - 1, leafSize, leafColor);
}