【问题标题】:requestAnimationFrame type error in object对象中的 requestAnimationFrame 类型错误
【发布时间】:2013-07-05 09:00:00
【问题描述】:

您好,我正在尝试在我的游戏中使用 requestAnimationFrame,实际上我在下面使用了这段代码,但正如您所见,“.bind()”为每个循环创建了一个新函数,这会减慢我的游戏速度……我是正在寻找最佳性能的“高效”解决方案,在此先感谢您:D

function myClass() {
  this.loop = function() {
    window.requestAnimationFrame(this.loop.bind(this));

    /* here myGameLoop */
  }

  this.loop();
}

上面的代码可以工作,但速度很慢。相反,这个“标准”代码给了我“类型错误”:

window.requestAnimationFrame(this);

我还发现我尝试了这个问答:requestAnimationFrame attached to App object not Window 只工作一次然后给出相同的“类型错误”:(

如果您不相信我,请尝试:http://jsfiddle.net/ygree/1 :'(

【问题讨论】:

    标签: html object canvas window requestanimationframe


    【解决方案1】:

    不知道你的对象的整个故事(里面还有什么);你可以通过这样做来简化生活:

    function myClass() {
    
        var iHavAccessToThis = 1;
    
        function loop() {
    
            iHavAccessToThis++;
    
            /* here myGameLoop */
    
            requestAnimationFrame(loop);
        }
        loop();
    
        //if you need a method to start externally use this instead of the above line
        this.start = function() { loop() }
    
        //...
        return this;
    }
    

    现在您不需要绑定任何东西,您可以快速访问本地范围。

    然后调用:

    var class1 = new myClass();
    class1.start();
    

    【讨论】:

    • 由于我正在编写一个 html5 框架,按照您的建议,我必须复制所有“外部可用”的方法和属性。所以...如果我有 100 个属性/方法,我必须编写其他 100 个方法来返回此属性...真的不好吗?无论如何感谢您的帮助
    • @user2488460 听起来像是一个巨大的项目。如果您发现它有帮助,也请考虑投票/接受答案。
    • 这不是我的第一个 html5 框架;) 但是我仍在为这个问题寻找更好的解决方案:'(
    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2015-01-14
    • 2021-11-16
    • 1970-01-01
    • 2012-06-09
    • 2022-12-20
    • 1970-01-01
    相关资源
    最近更新 更多