【发布时间】: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