requestAnimationFrame attached to App object not Window

依然范特西╮ 提交于 2019-12-11 11:05:45

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/12591250/requestanimationframe-attached-to-app-object-not-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!