【问题标题】:html pause canvas game works... but my resume does not. Why not?html 暂停画布游戏有效......但我的简历没有。为什么不?
【发布时间】:2019-01-07 11:08:40
【问题描述】:

目前正在开发一款画布游戏。我的暂停功能有效,但我的简历无效。我在这里看到了其他类似问题的例子,但它没有帮助。我做错了什么?

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);
},

【问题讨论】:

  • 与您遇到的问题无关,但我推荐此库用于键盘绑定craig.is/killing/mice
  • 不幸的是,对于这个项目,我不能使用 JS 库。它必须是香草js...耶!不过还是谢谢你!
  • 我不知道为什么pausedGame 会打电话给update...
  • 既然你的循环已经停止,你需要在暂停时恢复它是错误的,所以paused = !paused; if(paused === false) { gamearea.update(); //resume}
  • 我可以通过声明 paused = !paused; 来恢复循环来解决我的问题if (paused === false) { gamearea.update();游戏区.start();返回;

标签: javascript html css


【解决方案1】:

requestAnimationFrame 返回一个可用于“暂停”游戏循环的 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)
  }
}

【讨论】:

  • 不像 OP 那样调用 requestAnimationFrame 也会停止循环。他们的问题是恢复它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-26
相关资源
最近更新 更多