我使用Javascript和画布创建分形树。大部分代码来自我观看的视频教程,所以我对它不太熟悉。我控制了一些用滑块确定树的外观的方面。这是javascript:
var angle = 0;
var lengthV = 0;
var multiple = 0;
var branches = 2;
var min = 20;
var sliderA;
var sliderL;
var sliderM;
var sliderm;
function setup() {
var a = document.createTextNode("Angle");
document.body.appendChild(a);
sliderA = createSlider(0,TWO_PI, PI/4, 0.001); //slider to two pi, starts at pi/4, increments of 0.01
var l = document.createTextNode("Length");
document.body.appendChild(l);
sliderL = createSlider(0,500);
var m = document.createTextNode("Multiple");
document.body.appendChild(m);
sliderM = createSlider(0,0.8,0.4,0.01);
var i = document.createTextNode("Minimum");
document.body.appendChild(i);
sliderm = createSlider(1,400,10,1);
createCanvas(window.innerWidth,window.innerHeight);
}
function draw() {
background(255); //canvas colour
angle = sliderA.value();
lengthV = sliderL.value();
multiple = sliderM.value();
min = sliderm.value();
stroke(0); //line colour
translate(0.5*window.innerWidth, height) //sets new origin point for branch
branch(lengthV);
}
function branch(len) {
line(0, 0, 0, - len); //makes line
translate(0, -len);
if (len > min) { //ensure the branch is larger than minimum
if (branches == 2) {
push(); //save transformation state
rotate(angle); //rotate for first branch
branch(len * multiple); //repeat loop
pop(); //return back to original transformations state
push(); //save transformation state
rotate(-angle); //rotate other way for second branch
branch(len * multiple);
pop();
}
if (branches == 3) {
push(); //save transformation state
rotate(angle); //rotate for first branch
branch(len * multiple); //grow branch
pop(); //return back to original transformations state
push(); //save transformation state
rotate(0);
branch(len * multiple); //grow middle branch
pop(); //return back to original transformations state
push(); //save transformation state
rotate(-angle); //rotate other way for third branch
branch(len * multiple);
pop();
}
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
我有一个递归循环,它取决于branches
变量的值,以滑块改变的角度创建一组设定的分支。但是,我想知道是否有一种设置计时器的方法,以便在每个设定的时间段内增加一层分支,而不是一次增长。我对Javascript的了解有限,所以我感谢您给予的任何回复。