简体   繁体   English

RequestAnimationFrame 用于多个画布

[英]RequestAnimationFrame for multiple canvases

I've got a page with layered <canvas> elements like explained in the answer here .我有一个带有分层<canvas>元素的页面,如此答案中所述。 The canvases together make up an animation, so each is cleared and redrawn as necessary.画布一起构成了 animation,因此每个画布都在必要时被清除和重绘。

Now I'm trying to incorporate requestAnimationFrame by using the cross browser shim .现在我正在尝试通过使用跨浏览器 shim来合并requestAnimationFrame But I don't really know what requestAnimationFrame is doing behind the scenes.但我真的不知道requestAnimationFrame在幕后做了什么。

Is it okay to have it update multiple canvases in each loop?可以让它在每个循环中更新多个画布吗? Should each canvas have its own loop?每个 canvas 是否应该有自己的回路? Is the answer browser dependent?答案浏览器是否依赖?

Updating all the canvases in a single requestAnimationFrame is perfectly okay.在单个requestAnimationFrame中更新所有画布是完全可以的。

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.如果画布彼此独立并出现在页面的不同部分,那么您可能需要使用单独的requestAnimationFrame处理程序,将canvas元素作为第二个参数传递。 That way, only the currently visible canvases get updated.这样,只有当前可见的画布会得到更新。 (Passing an element as the second argument is WebKit-specific, though.) (不过,将元素作为第二个参数传递是特定于 WebKit 的。)

What requestAnimationFrame does is tell the browser that you would like to update the appearance of the page. requestAnimationFrame的作用是告诉浏览器您想要更新页面的外观。 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.当页面/元素可见时就会发生这种情况,并且永远不会比屏幕刷新率更频繁。

Using requestAnimationFrame simply lets the browser control when reflows/repaints on the page happen.使用requestAnimationFrame只是让浏览器控制页面上何时发生重排/重绘。

It would be better to alter all the canvases in one callback, so the browser can repaint them in one go.最好在一个回调中更改所有画布,以便浏览器可以在一个 go 中重新绘制它们。

This explanation of requestAnimationFrame was pretty helpful requestAnimationFrame 的这个解释很有帮助

The shim merely falls back to a timer if it is not available.如果垫片不可用,垫片只会退回到计时器。

You should be fine.你应该没事。 Update all of them in the same single loop.在同一个循环中更新所有这些。

requestAnimFrame isn't "tied" to a canvas or anything, just the function you pass it. requestAnimFrame没有“绑定”到 canvas 或任何东西,只是 function 你通过它。 So you can use it with three canvases or zero canvases just fine.因此,您可以将它与三个画布或零个画布一起使用就可以了。

use canvas in this format js file so RequestAnimationFrame for multiple canvas will work在这种格式的 js 文件中使用 canvas 以便多个 canvas 的 RequestAnimationFrame 将起作用

(function(){ ... })();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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