[英]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.