DAY 16
1
Modern Web

## 更加真實的骨幹

1. 當樹枝進行一節節生長時，需要不斷向上輸送營養，過程會有損耗
2. 當樹枝主幹要進行分岔時，營養會分別被兩個子樹枝給瓜分

1. shrink表示樹枝隨著一節節越來越短 (約0.55 - 0.65之間)
2. diff表示兩個子樹枝瓜分營養後，導致的長短差異 (約正負0.15之間)
``````if(times > 0){
let endX = x + r * Math.cos(theta / 180 * Math.PI);
let endY = y + r * Math.sin(theta / 180 * Math.PI);
let shrink = 0.65 + random(0.1); // from 0.55 to 0.65
let diff = random(0.3) - 0.15;  // +-0.15
this.son =
[new Tree(this, endX, endY, r * (shrink - diff), theta+30, times-1),
new Tree(this, endX, endY, r * (shrink + diff), theta-30, times-1)];
}
``````

diff 越少看起來越完美，越多則越容易有枝葉營養不良
shrink 越少整個樹越小

a: 若讓兩個分枝都增加角度，就能讓分枝逆時針綣曲，反之順時針
b: 若讓兩個分枝的正負角度更大，能讓分枝更加擴散，反之則是集中

``````let Tree = function(father, x, y, r, theta, times){
// ......
// 省略
// ......
this.Transform = function(index){
if(this.father){
this.theta = this.father.theta + 30 * ((index == 0)?(a+b+1):(a-b-1));
this.startX = this.father.endX;
this.startY = this.father.endY;
this.endX = this.startX + this.r * Math.cos(this.theta / 180 * Math.PI);
this.endY = this.startY + this.r * Math.sin(this.theta / 180 * Math.PI);
}
// 我是遞迴唷！還記得我嗎？
if(this.son) this.son.forEach((branch, index) => branch.Transform(index));
};
}
``````

``````canvas.addEventListener('click', Recreate);
function Recreate(e){
let Rect = canvas.getBoundingClientRect();
myTree = new Tree(undefined, WIDTH/2, HEIGHT, HEIGHT/6, -90, 10);
// 或者，讓它從滑鼠的位置長出來
// let x = (e.pageX - Rect.left) * RATIO;
// let y = (e.pageY - Rect.top) * RATIO;
// myTree = new Tree(undefined, x, y, HEIGHT/6, -90, 10);
}
``````

``````canvas.addEventListener('mousemove', GetMouse);
function GetMouse(e) {
let Rect = canvas.getBoundingClientRect();
a = ((e.pageX - Rect.left) * RATIO - WIDTH/2) / (WIDTH/2);
b = ((e.pageY - Rect.top) * RATIO - HEIGHT/2) / (HEIGHT/2);
myTree.Transform(); // 呼叫改變樹形狀的方法
}
``````

（到這邊本來有一個demo，不過我加了一些有的沒得進去，就爆炸了ww，等我修好明天再一起po）
（因為沒有備份，然後又想加入第二章的緩衝函式，製作風力效果，然後就出事了阿北，拍謝拉~）