HTML5 在单个页面上显示多个画布
如果我们在单个 html 页面上使用多个 是否会影响正在开发的应用程序的性能,并且代码是否会变得非常庞大并且需要更多时间来加载页面?
If we use multiple <canvas>
on a single html page does it hamper the performance of the application that is being developed and does the code get very bulky and require more time to load the page?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(5)
有时多个画布会带来更好的性能。最好测试一下你是否有时间。
假设您正在编写一个程序,该程序在屏幕上显示项目并允许用户绘制选择框。
使用一张画布,要绘制选择框,您必须一遍又一遍地重绘所有元素,以更新用户看到的选择框,因为它们都在同一画布上。
或者,您可以有两个画布,一个带有对象,然后另一个在前面用于诸如“工具”之类的东西(例如选择框图形)。这里两个画布可能更有效。
其他时候,您可能希望背景很少变化,而前景对象始终变化。您无需以每秒 60 帧的速度重绘所有对象,而是制作背景画布和前景画布,并且仅以较快的速度重绘前景对象。这里两个画布应该比一个画布更有效,但将背景画布“缓存”为图像并在每帧首先绘制图像可能更理想。
Sometimes multiple canvases results in better performance. It's best to test if you can afford the time.
Say you are making a program that has items on the screen and allows the user to draw a selection box.
With one canvas, to draw the selection box you'd have to redraw all of the elements over and over to update the selection box that the user sees since they are all on the same canvas.
Or, you can have two canvases, one with the objects and then another one in front for things like "tools" (like the selection box graphics). Here two canvases may be more efficient.
Other times you may want to have a background that changes very rarely and foreground objects that change all the time. Instead of redrawing all of them at 60 frames per second, you make a background canvas and foreground canvas, and only have the foreground's objects redraw at the fast speed. Here two canvases ought to be more efficient than one, but it may be more optimal to "cache" that background canvas as an image and drawing the image first each frame.
我已经在同一页面上使用了数十个画布,使用 JavaScript 图形库显示不同的图形。图表速度相当快,但在我们的例子中,它收集数据的速度有点慢。
如果您愿意,可以等待完成所有绘图,直到通过从
onLoad
函数启动页面的其余部分来加载。I've used dozens of canvases on the same page display different graphs using a javascript graphing library. The graphs are quite fast, it's gathering the data for them that's a bit slow in our case.
If you want you can wait to do all your drawing until the rest of the page loads by kicking it off from the
onLoad
function.根据 Mark Pilgrim 的说法,使用多个画布是个好主意。
请参阅此链接
使用多个画布可以通过隔离屏幕区域来更新和隔离输入事件来简化您的工作。如果您的页面非常适合划分屏幕区域,我建议您就这样做。
According to Mark Pilgrim, it's a good idea to use multiple canvases.
See This Link
Using multiple canvases can simplify things on your end, by isolating regions of the screen to update and isolating input events. If your page is well-suited for dividing-up regions of the screen, I say go for it.
另外, HTML5Rocks 说这是最好的方法:
Also, HTML5Rocks says it is a best approach:
单实例运行流畅,多了不影响页面渲染。数据是减慢画布速度的因素。为了增加页面加载时间,您可以简单地在页面加载后调用画布渲染方法。
A single instance runs smoothly, more does not affect rendering on page. Data is the factor of slowing canvas down. In order to increase page loading time, you can simply call canvas rendering methods after page loading.