var sketch = function (p) {
// Initial setup
p.setup = function () {
// Create the canvas
var canvas = p.createCanvas(600, 450);
// Paint a new tree each time the mouse is pressed inside the canvas
canvas.mousePressed(paintNewTree);
// We will just paint the tree once
p.noLoop();
p.noStroke();
// Paint the tree
paintNewTree();
};
/*
* This function creates a tree iteratively and paints it in the canvas
*/
function paintNewTree() {
var position = p.createVector(0.5 * p.width, 0.95 * p.height, 0);
var length = p.height / 7;
var diameter = length / 4.5;
var angle = -p.HALF_PI + (p.PI / 180) * p.random(-5, 5);
var color = p.color(130, 80, 20);
var level = 1;
var tree = new Branch(position, length, diameter, angle, color, level);
// Paint the tree
p.background(245);
tree.paint();
}
/*
* The Branch class
*/
function Branch(position, length, diameter, angle, color, level) {
this.position = position;
this.length = length;
this.diameter = diameter;
this.angle = angle;
this.color = color;
this.level = level;
this.middleBranch = this.createSubBranch(true);
this.extremeBranch = this.createSubBranch(false);
}
/*
* This method paints the branch and its sub-branches in the canvas
*/
Branch.prototype.paint = function () {
// Paint the middle branch
if (this.middleBranch) {
this.middleBranch.paint();
}
// Paint the extreme branch
if (this.extremeBranch) {
this.extremeBranch.paint();
}
// Calculate the diameter at the branch top
var topDiameter = 0.65 * this.diameter;
if (this.extremeBranch) {
topDiameter = this.extremeBranch.diameter;
}
// Paint the branch
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.