简体   繁体   中英

Why does this requestAnimationFrame setup fail to execute properly?

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

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

When I try to run this code directly, it works fine:

engine.renderCameras()
>>> render ok

When I try to run it using requestAnimationFrame, in either Chrome or Firefox, I get this:

window.requestAnimFrame(engine.renderCameras())
>>> render ok
>>> Error: Component returned failure code: 0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS) [nsIDOMWindow.mozRequestAnimationFrame]

It runs, but it always throws an error. That's not cool.

When I try to run it like this:

window.requestAnimFrame(engine.renderCameras)
>>> 0

It just does nothing.

I was able to solve this problem by using a closure, but I'd still like to know why I can't pass a function like that to requestAnimationFrame.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM