html暂停画布游戏有效...但是我的简历不起作用。为什么不呢?

时间:2019-01-07 02:57:35

标签: javascript html css

当前正在从事画布游戏。我的暂停功能有效,但我的简历无效。我在这里看到了其他类似问题的示例,但没有帮助。我在做什么错了?

var paused = false;

document.onkeydown = function onKeyPause(event) {
if (event.keyCode === 80)
    paused = !paused;
return;}

var gamearea = {
canvas: document.createElement("canvas"),
start: function () {
    this.canvas.width = 250;
    this.canvas.height = 287;

    ...more canvas css.........


update: function () {
    gamearea.context.clearRect(0, 0, 300, 400);
    document.getElementById("score").innerText = "Score: " + score;
    if (score == 20) {
        gamearea.stop(true);
        return;
    }
    if (targetGone()) {
        gamearea.stop(false);
        return;
    }

    if (paused) {
        gamearea.pausedGame(true);
        return;
    }

pausedGame: function (paused) {

    gamearea.canvas.removeEventListener("click", clickHandler, event);
    gamearea.context.fillRect(0, 100, 300, 100);
    gamearea.context.font = "20px helvetica";
    ... more canvas css ..

    if (paused) return; // <--- stop looping
    update();
    draw();
    window.requestAnimationFrame(loop, canvas);
},

1 个答案:

答案 0 :(得分:1)

requestAnimationFrame返回一个ID,您可以使用该ID“暂停”游戏循环

使用cancelAnimationFrame(RETURNED_ID)

简单的例子

// global variable
let loopId = null;

function start() {

  ...
  loopId = requestAnimationFrame(loop);
}

function loop() {
  ...
  loopId = requestAnimationFrame(loop);
}

function pauseHandler() {
  if (looId) {
    cancelAnimationFrame(loopId)
  }
}