gpt4 book ai didi

javascript - RangeError 与 requestAnimationFrame

转载 作者:搜寻专家 更新时间:2023-11-01 04:52:49 27 4
gpt4 key购买 nike

我收到以下错误:

RangeError: Maximum call stack size exceeded.

在这一行:

requestAnimFrame(Game.loop());

在这段代码中:

var Game = {
canvas: null,
context: null,
targetFps: 60,

init: function() {
canvas = document.getElementById('main-canvas');
context = canvas.getContext('2d');

// Resize canvas to match content
var content = document.getElementById('primary-content');
canvas.width = content.offsetWidth;
canvas.height = content.offsetHeight;

window.requestAnimFrame = (function() {
return window.requestAnimationFrame || // Chromium
window.webkitRequestAnimationFrame || // WebKit
window.mozRequestAnimationFrame || // Mozilla
window.oRequestAnimationFrame || // Opera
window.msRequestAnimationFrame || // IE
null;
})();

this.loop();
},

loop: function() {
requestAnimFrame(Game.loop());
},

update: function() {
// ...
},

draw: function() {
// Clear background with black
context.fillStyle = '#000';
context.fillRect(0, 0, canvas.width, canvas.height);
}
};

Game.init();
<div id="primary-content">
<canvas id="main-canvas" width="400" height="400"></canvas>
</div>

这可能是我忽略的明显问题,但我们将不胜感激。谢谢!

最佳答案

您正在立即调用该函数而不是传递它:

loop: function() {
requestAnimFrame(Game.loop());
}

只会一遍又一遍地执行 Game.loop()

你想要的是:

loop: function() {
requestAnimFrame(Game.loop);
}

这会将函数作为参数传递给 requestAnimFrame,而不是调用 Game.loop() 并传递结果 (undefined) .

关于javascript - RangeError 与 requestAnimationFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8771919/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com