1 | ## P5JS Tree
|
2 |
|
3 |
|
4 | ```p5js/playable
|
5 | var locs = [];
|
6 | function calcVec(x, y) {
|
7 | return new P5.Vector(y - x, - x - y);
|
8 | }
|
9 |
|
10 | function setupField() {
|
11 | p5.createCanvas(p5.windowWidth, p5.windowHeight);
|
12 |
|
13 | var res = 20;
|
14 | var countX = p5.ceil(p5.width/res) + 1;
|
15 | var countY = p5.ceil(p5.height/res) + 1;
|
16 |
|
17 | for (var j = 0; j < countY; j++) {
|
18 | for (var i = 0; i < countX; i++) {
|
19 | locs.push( new P5.Vector(res*i, res*j) );
|
20 | }
|
21 | };
|
22 |
|
23 | p5.noFill();
|
24 | p5.stroke(249,78,128);
|
25 | }
|
26 |
|
27 | function drawField() {
|
28 | // p5.background(30,67,137);
|
29 | for (var i = locs.length - 1; i >= 0; i--) {
|
30 | var h = calcVec( locs[i].x - p5.mouseX, locs[i].y - p5.mouseY);
|
31 | p5.push();
|
32 | p5.translate(locs[i].x, locs[i].y);
|
33 | p5.rotate(h.heading());
|
34 | p5.line(0, 0, 0, - 15);
|
35 | p5.pop();
|
36 | };
|
37 | }
|
38 |
|
39 |
|
40 |
|
41 | var theta1;
|
42 | var theta2;
|
43 |
|
44 | // Each branch now receives
|
45 | // its length as an argument.
|
46 | function branch(len, thick) {
|
47 | //function branch(len) {
|
48 | if (thick > 1){
|
49 | p5.strokeWeight(thick);
|
50 | }
|
51 | else{
|
52 | p5.strokeWeight(1);
|
53 | }
|
54 | p5.line(0, 0, 0, -len);
|
55 | p5.translate(0, -len);
|
56 |
|
57 | // Each branch’s length
|
58 | // shrinks by two-thirds.
|
59 | len *= 0.66;
|
60 | thick -= 1;
|
61 |
|
62 | if (len > 2) {
|
63 | p5.push();
|
64 | p5.rotate(theta1);
|
65 | // Subsequent calls to branch()
|
66 | // include the length argument.
|
67 | branch(len,thick);
|
68 | //branch(len);
|
69 | p5.pop();
|
70 |
|
71 | p5.push();
|
72 | p5.rotate(-theta2);
|
73 | branch(len,thick);
|
74 | //branch(len);
|
75 | p5.pop();
|
76 | }
|
77 | else{
|
78 | var c = p5.color(0, 255, 0);
|
79 | p5.fill(c);
|
80 | p5.ellipse(0,0,3,7);
|
81 | }
|
82 | }
|
83 |
|
84 | p5.windowResized = function() {
|
85 | p5.resizeCanvas(p5.windowWidth - 70, 500);
|
86 | };
|
87 |
|
88 | p5.setup = function() {
|
89 | setupField();
|
90 |
|
91 | p5.windowResized();
|
92 | };
|
93 |
|
94 | p5.draw = function () {
|
95 | p5.push();
|
96 | p5.background(255);
|
97 |
|
98 | theta1 = p5.map(p5.mouseX,0,p5.width,0,p5.PI/2);
|
99 | theta2 = p5.map(p5.mouseY,0,p5.height,0,p5.PI/2);
|
100 |
|
101 | // The first branch starts at the
|
102 | // bottom of the window.
|
103 | p5.translate(p5.width/2, p5.height);
|
104 | p5.stroke(0);
|
105 | branch(160,6);
|
106 | //branch(160);
|
107 | p5.pop();
|
108 | drawField();
|
109 | };
|
110 | ```
|
111 |
|
112 |
|
113 | ---
|
114 |
|
115 | [Back to Home](:@Home)
|
116 |
|