【问题标题】:Restart canvas javascript重新启动画布javascript
【发布时间】:2016-08-20 12:30:31
【问题描述】:

w3schoolslink有HTML5游戏教程

我正在尝试在画布下方添加一个按钮来重启游戏:

<button onmouseup="startGame()">Restart</button>

并在 for 循环中添加一个 clear 函数:

for (i = 0; i < myObstacles.length; i += 1) {
    if (myGamePiece.crashWith(myObstacles[i])) {
        myGameArea.stop();
        myGameArea.clear();
        return;
    } 
}

所以它清除了画布。

问题是函数 startGame() 不想重新开始游戏。 问题出在哪里?

问候

【问题讨论】:

    标签: javascript html loops canvas


    【解决方案1】:

    这就是我所做的:

    <button onmousedown="restart()">Restart</button>
    

    然后我定义了一个名为restart的新函数:

    function restart() {
        myGameArea.stop();
        myGameArea.clear();
        startGame();
    }
    

    它现在应该重新开始,但之前游戏的障碍仍然存在。要解决此问题,您需要在重新启动游戏之前清除 myObstacles 数组。我就是这样做的:

    function startGame() {
        myGamePiece = new component(30, 30, "red", 10, 120);
        myObstacles = []; // it is very important to do this before starting the game
        myGameArea.start();
    }
    

    在这里工作 jsfiddle:https://jsfiddle.net/11wrorox/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      • 2022-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-12
      相关资源
      最近更新 更多