I'm getting the following error:
RangeError: Maximum call stack size exceeded.
on this row:
requestAnimFrame(Game.loop());
in this piece code:
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>
It's probably something obvious I'm overlooking, but any help would be appreciated. Thanks!
Method 1: Update data via setInterval, and graphics via RAF. Keep those values in an object for each animated element. Assign the transform string to a variable in the object each setInterval 'frame'. Keep these objects in an array. Set your interval to your desired fps in ms: ms=(1000/fps).
requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser calls a specified function to update an animation before the next repaint. The method takes a callback as an argument to be invoked before the repaint.
Another reason requestAnimationFrame is so useful is the fact that it gives you a time variable which you can use to calculate the amount of time between frames. This is not something that setInterval will do and since setInterval is not 100% accurate it is very possible your animation will get messed up over time.
If your animation requires a different frames per second (up to 60 fps) or simply doesn't require that high a level of refresh rate, you can slow it down by calling requestAnimationFrame inside setTimeout() .
You are calling the function right away instead of passing it:
loop: function() {
requestAnimFrame(Game.loop());
}
Will just keep doing Game.loop()
over and over again.
What you want is:
loop: function() {
requestAnimFrame(Game.loop);
}
this will pass the function as an argument to requestAnimFrame
, instead of calling Game.loop()
and passing the result (undefined
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With