首页 > 解决方案 > p5.j​​s:滑块未正确更新

问题描述

我最近一直在学习 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>

标签: javascriptp5.js

解决方案


当我运行您的 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>


推荐阅读