setup()
setup() runs once when the sketch starts. It's the right place to size the canvas and calculate any values (like baseLength) that depend on the window's dimensions, plus set up drawing defaults like strokeCap().
function setup() {
createCanvas(windowWidth, windowHeight);
branchAngle = radians(25); // base split angle for branches
// initial trunk length based on canvas
baseLength = min(width, height) * 0.25;
// colors for branches
trunkColor = color(80, 42, 15); // dark brown
twigColor = color(150, 95, 45); // lighter brown
strokeCap(ROUND);
}
Line-by-line explanation (6 lines)
createCanvas(windowWidth, windowHeight);- Creates a canvas that fills the entire browser window.
branchAngle = radians(25); // base split angle for branches- Converts 25 degrees to radians (the unit p5.js's rotate() expects) and stores it for use in every branch split.
baseLength = min(width, height) * 0.25;- Sets the trunk's starting length to a quarter of whichever canvas dimension (width or height) is smaller, so the tree fits nicely on any screen shape.
trunkColor = color(80, 42, 15); // dark brown- Defines the RGB color used at the base of the tree (depth 0).
twigColor = color(150, 95, 45); // lighter brown- Defines the RGB color used at the outermost twigs (deepest recursion level) - the tree blends between these two colors by depth.
strokeCap(ROUND);- Rounds the ends of every line drawn afterward, so branch segments connect smoothly instead of showing sharp square joints.