Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RequestAnimationFrame for multiple canvases

I’ve got a page with layered <canvas> elements like explained in the answer here. The canvases together make up an animation, so each is cleared and redrawn as necessary.

Now I'm trying to incorporate requestAnimationFrame by using the cross browser shim. But I don’t really know what requestAnimationFrame is doing behind the scenes.

Is it okay to have it update multiple canvases in each loop? Should each canvas have its own loop? Is the answer browser dependent?

like image 799
Ritchie Avatar asked Dec 27 '22 19:12

Ritchie


2 Answers

Updating all the canvases in a single requestAnimationFrame is perfectly okay.

If the canvases are independent from each other and appear on different sections of the page, then you might want to use individual requestAnimationFrame handlers, passing the canvas element as the second argument. That way, only the currently visible canvases get updated. (Passing an element as the second argument is WebKit-specific, though.)

What requestAnimationFrame does is tell the browser that you would like to update the appearance of the page. The browser calls the callback when the page or element is next up for a redraw. And that’s going to happen when the page/element is visible, and never more often than the screen refresh rate.

like image 153
Ilmari Heikkinen Avatar answered Jan 11 '23 15:01

Ilmari Heikkinen


Using requestAnimationFrame simply lets the browser control when reflows/repaints on the page happen.

It would be better to alter all the canvases in one callback, so the browser can repaint them in one go.

This explanation of requestAnimationFrame was pretty helpful

like image 45
Divya Manian Avatar answered Jan 11 '23 15:01

Divya Manian