javascript - p5.js:滑块未正确更新
问题描述
我最近一直在学习 Javascript,我一直在关注 The Coding Train 的关于 p5js 中分形树的视频(此视频在这里https://www.youtube.com/watch?v=0jjeOYMjmDU)。
但是,我一直无法让角度滑块实际工作,因为每当我移动它时它似乎根本没有更新(在大约 10m 15s 的视频中,他的工作似乎几乎没有任何问题!)
有没有人可以对这个问题有所了解?我的代码如下:
let angle;
var slider; //let didnt work, got a "referenceerror cannot access before initialization"
function setup() {
createCanvas(400, 400);
slider = createSlider(0, TWO_PI, PI/4, 0.01);
}
function draw() {
background(51);
console.log(isLooping()); //debug - prints 'true'
angle = slider.value();
console.log(angle); //debug - wrote to test the slider, isn't continually printing, why?
// let len = 100;
stroke(255);
translate(200, height);
branch(100);
}
function branch(len) {
line(0, 0, 0, -len);
translate(0, -len);
rotate(angle); // should change when i move the slider, but doesn't
branch(len * 0.67);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.2.0/p5.min.js"></script>
解决方案
当我运行您的 p5 草图时,出现递归错误:
Uncaught RangeError: Maximum call stack size exceeded (sketch: line 24)
您的分支函数永远不会返回,因为它会无限次调用自己。我进行了一些编辑,另请参阅我的内联评论。
let angle;
let slider; //let works fine
function setup() {
createCanvas(400, 400);
slider = createSlider(0, TWO_PI, PI/4, 0.01);
}
function draw() {
background(51);
console.log(isLooping()); //debug - prints 'true'
angle = slider.value();
console.log(angle); //debug - wrote to test the slider, isn't continually printing, why?
// let len = 100;
stroke(255);
translate(200, height);
branch(100, 4); // adjust the second argument to reflect your desired depth of the tree
}
function branch(len, depth) {
if(depth == 0){
return
}
line(0, 0, 0, -len);
translate(0, -len);
rotate(angle); // should change when i move the slider, but doesn't
branch(len * 0.67, depth - 1); //calling the recursive function with the 'remaining' branches
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.2.0/p5.min.js"></script>
推荐阅读
- python - 如何从 PyQt5 中的 item() 方法获取对象?
- c - 如何写表达式 a<=20?b=30:c=30; 这样 30 只使用一次?
- json - 从 Api 登录后,我得到了 json 的响应。现在需要将数组长度显示为我的通知图标的计数。怎么做?
- python - 如何使用自动填充字段提取表单数据(使用python+selenium+chrom webdriver)
- php - 蛋糕PHP。如何给出显示图像的路径
- java - 如何使用带有 OnClickListener 的 ViewPager 制作数组列表按钮?
- python - 创建组并在 pyplot 上显示总和
- css - CSS 只为样式选择数字
- python - 如何将 Python 解释器添加到 .Net Core Docker 映像?
- css - 调整屏幕上的 div 从 1200 像素(及以上)更改为移动