我怎样才能 运行 我的功能只有在按下一个键后?

How can I run my function only after a key is pressed?

我想运行按键时startDraw()函数,按键后一直运行。我尝试使用 if(mouseIsPressed) 语句和 p5.js 中预定义的 mousePressed() 函数,但它仅 运行 小于 1 的 startDraw() 函数秒(按下键的时间)。

function draw(){
    background(220);

    startDraw();
}

例如:

function draw(){

    if (mouseIsPressed) {
        startDraw();
    }
}

这仅在按键按下期间有效,之后无效。

创建一个已初始化的状态变量 (drawing) False 并在 mousePressed() 回调中设置它 True

let drawing = False;

function draw(){
      background(220);

      if (drawing) {
          startDraw();
      }
}

function mousePressed() {
    drawing = True;
}

或者,您可以在按下鼠标时 noLoop() and start it by loop() 停止执行 draw() 来启动应用程序:

function setup() {

    // [...]

    noLoop();
}   

function mousePressed() {
    loop();
}

function draw(){
    background(220);
    startDraw();
}