目前正在开发 Canvas 游戏。我的暂停功能有效,但我的简历无效。我在这里看到了其他类似问题的例子,但它没有帮助。我做错了什么?
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);
},
最佳答案
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)
}
}
关于javascript - html 暂停 Canvas 游戏有效...但我的简历没有。为什么不?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54068070/