简体   繁体   English

如何仅在按下一个键后运行我的 function?

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

I want to run the startDraw() function when I press a key, and have it run constantly after the key is pressed.我想在按下一个键时运行startDraw() function,并在按下键后让它不断运行。 I tried to use the if(mouseIsPressed) statement, and the mousePressed() function that is predefined in p5.js, however it only runs the startDraw() function for less than 1 second (the time that the key is pressed).我尝试使用if(mouseIsPressed)语句和 p5.js 中预定义的mousePressed() function,但是它只运行startDraw() function 不到 1 秒(按下键的时间)。

function draw(){
    background(220);

    startDraw();
}

For instance:例如:

function draw(){

    if (mouseIsPressed) {
        startDraw();
    }
}

This only works for the duration of the period that a key is pressed, not afterwards.这仅适用于按下键期间的持续时间,而不是之后。

Create a state variable ( drawing ) which is initialized False and set it True in the mousePressed() callback:创建一个初始化为False的 state 变量( drawing ),并在mousePressed()回调中将其设置为True

let drawing = False;

function draw(){
      background(220);

      if (drawing) {
          startDraw();
      }
}

function mousePressed() {
    drawing = True;
}

Alternatively you can start the application with the execution of draw() stopped, by noLoop() and start it by loop() when the mouse is pressed:或者,您可以通过noLoop() draw()来启动应用程序,并在按下鼠标时通过loop()启动它:

function setup() {

    // [...]

    noLoop();
}   

function mousePressed() {
    loop();
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 按下回车键时如何执行JavaScript函数 - How can I execute JavaScript function when the enter key is pressed 如果在特定时间段内多次按下Tab键,我如何仅触发一个Tab键 - how can i trigger only one tab key if the tab key is pressed numerous times in a certain time period JS / Canvas - 如何仅在按下键时更新 draw() 函数? - JS / Canvas - How do I update the draw() function only when key is pressed? 按下回车键后如何触发onSubmit功能? - How do I trigger my onSubmit function when the enter key is pressed? 我怎样才能让我的程序检查所选单词中是否有按下的键 - How can I get my program to check if a pressed key is in a selected word 如何让我的程序将字符串与在字符串的特定部分中按下的键交换? - How can I get my program to swap a string with the key that is pressed down in a specific section of the string? 我可以制作一个 function 根据按下的键返回一个 integer (nodejs) - Can i make a function that returns an integer based on the key pressed (nodejs) 如何仅在 textarea 完全加载后运行 controller function? - How can I run a controller function only after textarea fully loaded? 仅在Angular中发出$ http请求后,才能运行javascript函数? - How can I run a javascript function only after a $http request has been made in Angular? 如何仅在单击按钮时运行表格过滤器功能? - How can I run my table filter function only when clicking a button?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM