-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproceduralTree.js
99 lines (79 loc) · 2.55 KB
/
proceduralTree.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//guarantees app exists
var app = app || {};
"use strict";
app.Tree = function() {
//Globals
var gStartingX; //x coordinate of the base of the tree, defaulted to 0
var gStartingY; //y coordinate of the base of the tree, defaulted to 0
var gStrokeStyle;
var gLineCap = "round";
var gStartingLength;
var gStartingLineWidth = 1;
var gCurrentLineWidth;
var gTheta;
var gFalloff = 0.7;
var canvas;
var ctx;
function Tree(thatCanvas, x, y, strokeStyle, startingLength) {
//"optional parameters"
strokeStyle = strokeStyle || "black";
startingLength = startingLength || 50;
//set initial values
this.gStrokeStyle = strokeStyle;
this.gStartingLength = startingLength;
this.gStartingX = x;
this.gStartingY = y;
//set up canvas
this.canvas = thatCanvas;
this.ctx = this.canvas.getContext("2d");
this.ctx.lineWidth = gStartingLineWidth;
}
Tree.prototype.setAngle = function(theta) {
this.gTheta = theta;
}
Tree.prototype.getAngle = function() {
return this.gTheta;
}
Tree.prototype.getStrokeStyle = function() {
return this.gStrokeStyle;
}
Tree.prototype.getStartingLength = function() {
return this.gStartingLength;
}
Tree.prototype.getX = function() {
return this.gStartingX;
}
Tree.prototype.getY = function() {
return this.gStartingY;
}
Tree.prototype.draw = function() {
this.ctx.save();
gCurrentLineWidth = gStartingLineWidth;
this.ctx.strokeStyle = this.gStrokeStyle;
this.ctx.lineCap = gLineCap;
this.ctx.beginPath();
this.drawBranch(this.gStartingX, this.gStartingY, this.gStartingLength);
this.ctx.stroke();
this.ctx.restore();
}
Tree.prototype.drawBranch = function(x, y, length, rotation) {
rotation = rotation || 0;
this.ctx.lineWidth = gCurrentLineWidth;
//--gCurrentLineWidth;
this.ctx.translate(x, y);
this.ctx.rotate(rotation);
this.ctx.moveTo(0, 0);
this.ctx.lineTo(0, -length);
if (length > 10)
{
//save the context and call drawBranch after rotating the canvas
this.ctx.save();
this.drawBranch(0, -length, length * gFalloff, this.gTheta);
this.ctx.restore();
this.ctx.save();
this.drawBranch(0, -length, length * gFalloff, -this.gTheta);
this.ctx.restore();
}
}
return Tree;
}();