RequestAnimationFrame的RangeError

jdl*_*dlm 5 html javascript canvas

我收到以下错误:

RangeError: Maximum call stack size exceeded.
Run Code Online (Sandbox Code Playgroud)

在这一行:

requestAnimFrame(Game.loop());
Run Code Online (Sandbox Code Playgroud)

在这段代码中:

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();
Run Code Online (Sandbox Code Playgroud)

这可能是我忽视的明显的东西,但任何帮助都会受到赞赏.谢谢!

Esa*_*ija 14

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

loop: function() {
        requestAnimFrame(Game.loop());
    }
Run Code Online (Sandbox Code Playgroud)

只会Game.loop()一遍又一遍地做.

你想要的是:

loop: function() {
        requestAnimFrame(Game.loop);
    }
Run Code Online (Sandbox Code Playgroud)

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