【问题标题】:requestAnimationFrame attached to App object not WindowrequestAnimationFrame 附加到 App 对象而不是 Window
【发布时间】:2012-09-25 21:22:21
【问题描述】:

我已经设置了以下jsFiddle http://jsfiddle.net/ZbhQY/4/

我正在使用一个小的 requestAnimationFrame polyfill 并将结果返回给 window.reqeuestAnimFrame 这一切正常,并且对该函数的所有调用都按预期工作。

如果我将其更改为返回到 game.reqeuestAnimFrame 并将所有对 window.reqeuestAnimFrame 的调用替换为新的 game.reqeuestAnimFrame 它将不再起作用。

有人能解释一下为什么会这样吗?我可以做些什么来完成这项工作? 谢谢。

【问题讨论】:

    标签: javascript html canvas requestanimationframe


    【解决方案1】:

    requestAnimationFrame 必须具有window 的上下文才能正常运行。

    您可以将调用重写为:

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

    它将按预期运行。

    您遇到的错误是因为 requestAnimationFrame 期望它的上下文 (this) 是 window,但它的上下文是 game

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

    或者,您可以像这样重写您的 requestAnimFrame getter:

    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);
            };            
        })();
    

    这将允许您像您期望的那样调用game.requestAnimFrame(game.run)

    【讨论】:

    • 非常感谢 =) 我在这上面挂了两个小时。您的通话解决方案非常简单。我不知道,rAF 必须在窗口上下文中。现在一切都清楚了 =)
    猜你喜欢
    • 2021-11-09
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 2010-10-11
    • 2011-06-25
    • 2018-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多