フラクタルな木の描画
https://github.com/shiffman/The-Nature-of-Code-Examples-p5.js/tree/master/chp08_fractals/NOC_8_06_Tree https://gyazo.com/1a1e476d9b51f27040c0f9843ec176ae
サンプルを持ってきた 増井俊之.icon
短いコードなのに動きが面白い
code:tree.js
// The Nature of Code
// Daniel Shiffman
// Recursive Tree
// Renders a simple tree-like structure via recursion
// Branching angle calculated as a function of horizontal mouse position
var theta;
function setup() {
createCanvas(640, 360);
}
function draw() {
background(51);
// Let's pick an angle 0 to 90 degrees based on the mouse position
theta = map(mouseX,0,width,0,PI/2);
// Start the tree from the bottom of the screen
translate(width/2, height);
stroke(255);
//branch(120);
branch(mouseY); // Y座標で深さを変えるようにしてみた
}
function branch(len) {
// Each branch will be 2/3rds the size of the previous one
var sw = map(len,2,120,1,10);
strokeWeight(sw);
//strokeWeight(2);
line(0, 0, 0, -len);
// Move to the end of that line
translate(0, -len);
len *= 0.66;
// All recursive functions must have an exit condition!!!!
// Here, ours is when the length of the branch is 2 pixels or less
if (len > 2) {
push(); // Save the current state of transformation (i.e. where are we now)
rotate(theta); // Rotate by theta
branch(len); // Ok, now call myself to draw two new branches!!
pop(); // Whenever we get back here, we "pop" in order to restore the previous matrix state
// Repeat the same thing, only branch off to the "left" this time!
push();
rotate(-theta);
branch(len);
pop();
}
}