I have set up the following jsFiddle http://jsfiddle.net/ZbhQY/4/

Im using a small requestAnimationFrame polyfill and returning the result to window.reqeuestAnimFrame this all works fine and all calls to this function work as expected.

If i change this to return to game.reqeuestAnimFrame and replace all calls to window.reqeuestAnimFrame to the new game.reqeuestAnimFrame it no longer works.

Could someone please explain why this is the case and what i could do in order to make this work? Thanks.

有帮助吗?

解决方案

requestAnimationFrame must have a context of window to function properly.

You can rewrite your call as:

game.requestAnimFrame.call(win, game.run);

and it will function as expected.

The error you were running into is because requestAnimationFrame expects its context (this) to be window, but instead its context was game.

http://jsfiddle.net/ZbhQY/5/

Alternatively, you could rewrite your requestAnimFrame getter like so:

game.requestAnimFrame = (function() {
        var rAF = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
        function(callback) {
            window.setTimeout(callback, 1000 / 60);
        };

        return function(callback){
            rAF.call(window, callback);
        };            
    })();

This would allow you to call game.requestAnimFrame(game.run) as you would expect.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top