【发布时间】:2020-06-12 13:20:37
【问题描述】:
我正在使用 p5.js 在 html5 convas 中创建生长树。
我想平滑地生成以下树,而不是一次生成。
function setup(){
createCanvas(600,600);
noLoop();
}
function draw(){
background(255);
strokeWeight(10);
translate(width/2,height-20);
branch(0);
}
function branch(depth){
if (depth < 10) {
line(0,0,0,-height/10); // draw a line going up
{
translate(0,-height/10); // move the space upwards
rotate(random(-0.05,0.05)); // random wiggle
if (random(1.0) < 0.6){ // branching
rotate(0.3); // rotate to the right
scale(0.8); // scale down
push(); // now save the transform state
branch(depth + 1); // start a new branch!
pop(); // go back to saved state
rotate(-0.6); // rotate back to the left
push(); // save state
branch(depth + 1); // start a second new branch
pop(); // back to saved state
}
else { // no branch - continue at the same depth
branch(depth);
}
}
}
}
function mouseReleased(){
redraw();
}
html, body {
margin: 0;
padding: 0;
}
<script src="https://cdn.jsdelivr.net/npm/p5@0.10.2/lib/p5.js"></script>
<!DOCTYPE html><html><head>
</head>
<body>
<script src="sketch.js"></script>
</body></html>
我正在使用 setTimeout 函数来延迟每个递归分支以使树顺利生长。
但是得到了意想不到的形状
function setup(){
createCanvas(600,600);
noLoop();
}
function draw(){
background(255);
strokeWeight(10);
translate(width/2,height-20);
branch(0);
}
function branch(depth){
setTimeout(function() {
if (depth < 10) {
line(0,0,0,-height/10); // draw a line going up
{
translate(0,-height/10); // move the space upwards
rotate(random(-0.05,0.05)); // random wiggle
if (random(1.0) < 0.6){ // branching
rotate(0.3); // rotate to the right
scale(0.8); // scale down
push(); // now save the transform state
branch(depth + 1); // start a new branch!
pop(); // go back to saved state
rotate(-0.6); // rotate back to the left
push(); // save state
branch(depth + 1); // start a second new branch
pop(); // back to saved state
}
else { // no branch - continue at the same depth
branch(depth);
}
}
}
}, 500);
}
function mouseReleased(){
redraw();
}
html, body {
margin: 0;
padding: 0;
}
<script src="https://cdn.jsdelivr.net/npm/p5@0.10.2/lib/p5.js"></script>
<!DOCTYPE html><html><head>
</head>
<body>
<script src="sketch.js"></script>
</body></html>
请提供任何解决方案以使树顺利生长(而不是立即)。
【问题讨论】:
标签: javascript recursion html5-canvas settimeout p5.js