Why does this requestAnimationFrame setup fail to execute properly?

后端 未结 1 1340
广开言路
广开言路 2021-01-16 17:28

The function to render my canvas is a prototyped method of a class, like this:

Engine.prototype.renderCameras = function() {
        console.log(\'render ok\');
}         


        
相关标签:
1条回答
  • 2021-01-16 17:59
    window.requestAnimFrame(engine.renderCameras())
    

    is not passing a function to requestAnimFrame, it is passing the return value of engine.renderCameras to requestAnimFrame. The return value is probably not a function and that's why you get this error.

    window.requestAnimFrame(engine.renderCameras)
    

    instead correctly passes a function reference, but then this [docs] inside renderCameras won't refer to engine. If you rely on that (which I assume based on the setup), you either have to pass a function calling engine.renderCameras properly:

    window.requestAnimFrame(function(){
        engine.renderCameras();
    });
    

    or use .bind [docs] to set (and bind) this explicitly:

    window.requestAnimFrame(engine.renderCameras.bind(engine));
    

    Either way, you have to repeatedly call window.requestAnimFrame to get the next animation frame, which means you typically use a recursive function. For example:

    window.requestAnimFrame(function render(){
        engine.renderCameras();
        window.requestAnimFrame(render);
    });
    
    0 讨论(0)
提交回复
热议问题