首页 > 解决方案 > 有没有办法只在事件发生后运行 p5.js?

问题描述

我只想在三个输入字段都不为空并且单击按钮后运行 p5.jsdraw()和函数。setup()

function roundNumber(num, decimal_places) {
  if (!("" + num).includes("e")) {
    return +(Math.round(num + "e+" + decimal_places) + "e-" + decimal_places);
  } else {
    var arr = ("" + num).split("e");
    var sig = ""
    if (+arr[1] + scale > 0) {
      sig = "+";
    }
    return +(Math.round(+arr[0] + "e" + sig + (+arr[1] + decimal_places)) + "e-" + decimal_places);
  }
} /* From https://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary */

function computeSelection() {
  const expr = document.forms[0].mathExpr.value;
  var tempAns = parseFloat(eval(expr));
  var roundedAnswer = roundNumber(tempAns, 10);
  var answer = roundedAnswer;
  document.getElementById("output").textContent = answer;
}

function get_x_min_x_max() {
  const x_min = $("#x_min").value;
  const x_max = $("#x_max").value;
  var x_min_x_max = [x_min, x_max];
  return x_min_x_max;
}

function setup() {
  createCanvas(300, 300);
}

function draw() {

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
  <form>
    <label>Graph y=</label>
    <input id="mathExpr" type="text" name="mathExpr" value="">
    <label> from x=</label>
    <input id="x_min" type="text" name="x_min" value="">
    <label> to </label>
    <input id="x_max" type="text" name="x_max" value="">
    <input type="button" name="result" value="Result" onclick="computeSelection();">
  </form>
  <h2>Answer: <span id="output"></span></h2>
</body>

如果这是我的代码,我只希望 js 代码底部的绘制和设置运行一次mathExprx_min并且x_max都包含一些文本并单击结果按钮。我怎样才能做到这一点?

标签: javascriptfunctionprocessingp5.js

解决方案


对于您想做的事情,您可以使用noLoop()andloop()指令。
noLoop()停止 p5.js 继续执行draw()loop()恢复它。

noLoop()指令添加到draw(). 这会导致循环在 1 次执行后停止。

function draw() {
    noLoop()
    // [...]
}

向此添加loop()指令computeSelection() 会导致循环恢复。抽签将noLoop()在 1 次执行后再次停止:

function computeSelection() {
    // [...]
    loop()
}

推荐阅读