xxxxxxxxxx
// sample code adapted from Pearson (2011)
// coding a fractal structure: self-similarity (Pearson 2011:159-160)
// adding self-reference (Pearson 2011:161-162)
// adding animation (Pearson 2011:163-164)
// adding controls (Pearson 2011:164-165)
// monkeyjack8204@gmail.com, DPD 2020
// 希望創造出一個聖誕節卡片的感覺.綠色但有點噁心
let _numChildren = 6;
let _maxLevels = 4;
let _trunk;
function setup() {
createCanvas(windowWidth,windowHeight);
background(255);
noFill();
newTree();
}
function draw() {
frameRate(24);
background(100);
_trunk.updateMe(width/2, height/2);
_trunk.drawMe();
}
function newTree() {
_trunk = new Branch(1, 0, width/2, 50);
_trunk.drawMe();
}
// ========== object =============
class Branch {
constructor(lev, ind, ex, ey) {
this.level = lev;
this.index = ind;
this.x; this.y; this.endx; this.endy;
this.stroke = (1/this.level)*10;
this.alph = 255/this.level;
this.len = (1/this.level)*random(200);
this.lenChange = random(10)-5;
this.rot = 0;
this.rotChange = random(10)-5;
this.children = [];
if (this.level < _maxLevels) {
for (let i=0; i<_numChildren; i++) {
let nb = new Branch(this.level+1, i, 0, 0);
this.children.push(nb);
}
}
this.updateMe(ex, ey);
}
updateMe(nx, ny) {
this.x = nx;
this.y = ny;
// recalculate end points
this.rot += this.rotChange;
this.len -= this.lenChange;
if (this.len<0 || this.len>200) {
this.lenChange *= -1;
}
let r = radians(this.rot);
this.endx = this.x + this.len*cos(r);
this.endy = this.y //+ this.len*sin(r);
for (let i=0; i<this.children.length; i++) {
this.children[i].updateMe(this.endx, this.endy);
}
}
drawMe() {
strokeWeight(1);
noStroke(205,216,115);
fill(255, this.alph);
line(this.x, this.y, this.endx, this.endy);
ellipse(this.x, this.y, this.len/12, this.len/12);
for (let i=0; i<this.children.length; i++) {
this.children[i].drawMe();
}
fill(208,59,59,this.alph);
circle(this.x, this.y, 20);
fill(144,26,26,this.alph);
circle(this.x+100, this.y+100, 40);
fill(255,this.alph);
//frameRate(4);
circle(random(0,width),random(0,height),random(0,40));
}
}