首页 > 解决方案 > 如何在 javascript 画布中为不同的事物重用相同的密钥?

问题描述

在画布中,我希望能够使用回车键做一件事,然后再次按下它来做另一件事。

例如,

if(enterPressed) {

   // do one thing


}

if (enterPressed) {

    //Do some other thing


}

问题是当我按下回车键时,它会自动同时执行这两项操作,而我希望它希望它分别执行每个语句。

对于更多上下文,我想做的类似于口袋妖怪游戏中的文本样式,其中游戏将显示一些文本,然后等到您按下按钮然后显示下一组文本。

标签: javascripthtml5-canvasdraw

解决方案


问题中的示例代码连续有两个语句,我假设这是您想要处理的方式enterPressed

要进行第二个(或第三个或更多)操作,您需要存储输入操作的状态。例如,这是第一次印刷吗?

// this in the setup code.
var enterAction = "firstPress"

然后每次enterPressed处理时,您还必须检查状态,以便发生正确的操作。

if (enterPressed && enterAction === "firstPress") {

当您处理该操作时,您还设置了要处理的下一个状态。因为您连续有两个语句都检查是否enterPressed为真,所以您还需要表明您已经处理了新闻。这可以只是设置enterPressed = false

    enterAction = "secondPress";
    enterPressed = false; 
}

因此你的代码看起来像

// Init the first enter state
const FIRST = 1, SECOND = 2;
var enterAction = FIRST;

并将问题代码替换为

// Handling first press
if (enterPressed && enterAction === FIRST) {
    enterAction = SECOND;  // set action for next press
    enterPressed = false;  // clear press to indicate its been handled

    // do one thing
}

// Handling second press
if (enterPressed && enterAction === SECOND) {
    enterAction = FIRST;    // set action for next press
    enterPressed = false;   // clear press to indicate its been handled

    //Do some other thing
}    

推荐阅读