为什么 RenderingContext.drawElements 在绘制之前清空屏幕?

Why is RenderingContext.drawElements clearing the screen before it draws?

RenderingContext.drawElements在绘制前清屏是否正确?

考虑这些屏幕截图,这些屏幕截图显示了调用 drawElements 的一个步骤,其中已绘制的对象已被擦除。

WebGL 有效 在页面合成后清除屏幕。当您一次一行地完成内容时,每次停止时都会合成它。

如果您不想清除它,请在创建 WebGL 上下文时请求 preserveDrawingBuffer: true,如

gl = someCanvas.getContext("webgl", { preserveDrawingBuffer: true });

至于为什么,from the spec

While it is sometimes desirable to preserve the drawing buffer, it can cause significant performance loss on some platforms. Whenever possible this flag should remain false and other techniques used. Techniques like synchronous drawing buffer access (e.g., calling readPixels or toDataURL in the same function that renders to the drawing buffer) can be used to get the contents of the drawing buffer. If the author needs to render to the same drawing buffer over a series of calls, a Framebuffer Object can be used.

Implementations may optimize away the required implicit clear operation of the Drawing Buffer as long as a guarantee can be made that the author cannot gain access to buffer contents from another process. For instance, if the author performs an explicit clear then the implicit clear is not needed.

TL;DR 版本是 preserveDrawingBuffer: false(默认)允许 WebGL 在合成时交换缓冲区(这并不意味着它会交换缓冲区,但如果它选择的话它可以)。 preserveDrawingBuffer: true 表示它不能交换缓冲区,它必须复制缓冲区。复制比交换慢得多。