我知道将图形预渲染到屏幕外画布通常更快。像圆形这样简单的形状就是这种情况吗?以类似游戏的帧速率渲染 100 个圆圈会产生显着差异吗?50圈?25?
2 回答
要将其分解为两个略有不同的问题,您要问的内容有两个方面:
1) 在屏幕外绘制一个形状并更快地把它放到屏幕上
2) 绘制一个形状一次并将其复制到 100 个不同的地方比绘制一个形状 100 次要快
第一个问题的答案是“视情况而定”。
这是一种称为“缓冲”的技术,它与速度无关。
缓冲图像的目的是消除图像的抖动。
如果您在屏幕上绘制所有内容,那么当您遍历所有对象并绘制它们时,它们会实时更新。
在 NES 时代,这很正常,因为内存没有太多空间,也没有太多的能力来做任何事情,而且由于程序员的知识不多,他们必须使用的指令有限。
但如今,这并不是游戏真正做事的方式。
通常,他们调用一帧的所有绘制更新,然后将整个帧作为完成的图像,并将整个内容粘贴到屏幕上。
默认情况下,GPU(和 GL/DirectX)在一个称为“双缓冲”的过程中处理这个问题。
这是一个双缓冲区,因为用于更新的“进行中”缓冲区以及保存最后一帧的最终图像的缓冲区都有空间,监视器正在读取这些图像。
在帧处理结束时,缓冲区将“交换”。新的完整帧将被发送到监视器,旧帧将被来自其他绘制调用的新图像数据覆盖。
现在,在 HTML5 中,并没有真正访问帧缓冲区,所以我们自己做;对屏幕外画布进行每次绘制调用。当所有更新完成(图像稳定)后,将整个图像复制并粘贴到屏幕画布上。
这里有一个很大的速度优化,称为“blitting”,它基本上只复制已更改的部分,并重用旧图像。
除了这些,还有很多需要注意的地方,这些天,因为我们添加了所有的特殊效果,但它确实存在。
The second part of your question has to do with a concept called "instancing".
Instancing is similar to blitting, but while blitting is about only redrawing what's changed, instancing is about drawing the exact same thing several times in different places.
Say you're painting a forest in Photoshop.
You've got two options:
- Draw every tree from scratch.
- Draw one tree, copy it, paste it all over the image.
The downside of the second one is that each "instance" of the image looks exactly the same.
If your "template" image changes colour or takes damage, then all instances of the image do, too.
Also, if you had 87 different tree variations for an 8000 tree forest, making instances of them all would still be very fast, but it would take more memory, because you now need to save 87x more images than when it was just one tree, to reference on every draw call.
The upside is that it's still much, much faster.
To answer your specific question about X circles, versus instancing 1 circle:
Yes, it's still going to be a lot faster.
What a "lot" means, though, will change based on a lot of different things, because now you're talking about browsers on PCs.
How strong is the PC?
How good is the videocard?
How large is the canvas in software-pixels (not CSS pixels)?
How large are the circles? Do they have alpha-blending?
Is this written in WebGL or software?
If software is the canvas compositing in hardware mode?
For a typical PC, you should still be able to hit 60fps in Chrome, drawing 20 circles, I think (depending on what you're doing to them... ...just drawing them onscreen, every frame is simple), so in this case, the instances are still a "lot" faster, but it's not going to matter, because you've already passed the performance-ceiling of Canvas.
I don't know that the same would be true on phones/tablets, or battery-powered laptops/netbooks, though.
是的,从屏幕外的画布转移甚至比像圆弧这样的原始绘图还要快。
那是因为 GPU 只是从屏幕外画布复制像素(不需要太多 CPU 工作)