-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcanvas3.html
More file actions
66 lines (64 loc) · 2.05 KB
/
canvas3.html
File metadata and controls
66 lines (64 loc) · 2.05 KB
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
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="jquery.js">
</script>
<script type="text/javascript">
var drawTree = function (ctx, startX, startY, length, angle, depth, branchWidth) {
var rand = Math.random,
newLength, newAngle, newDepth, maxBranch = 3,
endX, endY, maxAngle = 2 * Math.PI / 4,
subBranches, lenShrink;
// Draw a branch, leaning either to the left or right (depending on angle).
// First branch (the trunk) is drawn straight up (angle = 1.571 radians)
ctx.beginPath();
ctx.moveTo(startX, startY);
endX = startX + length * Math.cos(angle);
endY = startY + length * Math.sin(angle);
ctx.lineCap = 'round';
ctx.lineWidth = branchWidth;
ctx.lineTo(endX, endY);
// If we are near the end branches, make them green to look like leaves.
if (depth <= 2) {
ctx.strokeStyle = 'rgb(0,' + (((rand() * 64) + 128) >> 0) + ',0)';
}
// Otherwise, choose a random brownish color.
else {
ctx.strokeStyle = 'rgb(' + (((rand() * 64) + 64) >> 0) + ',50,25)';
}
ctx.stroke();
// Reduce the branch recursion level.
newDepth = depth - 1;
// If the recursion level has reached zero, then the branch grows no more.
if (!newDepth) {
return;
}
// Make current branch split into a random number of new branches (max 3).
// Add in some random lengths, widths, and angles for a more natural look.
subBranches = (rand() * (maxBranch - 1)) + 1;
// Reduce the width of the new branches.
branchWidth *= 0.7;
// Recursively call drawTree for the new branches with new values.
for (var i = 0; i < subBranches; i++) {
newAngle = angle + rand() * maxAngle - maxAngle * 0.5;
newLength = length * (0.7 + rand() * 0.3);
drawTree(ctx, endX, endY, newLength, newAngle, newDepth, branchWidth);
}
};
$(function() {
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
drawTree(ctx, 320, 470, 60, -Math.PI/2, 12, 12);
});
</script>
<style type="text/css">
.dragger {width:10px; height:10px;z-index:1}
#mycanvas {border:1px solid;position:absolute;top:0px;}
</style>
</head>
<body style="position:relative;">
<canvas id="mycanvas" width=500, height=500>
</canvas>
</body>
</html>