实现对webgl的播放器进行截图功能, 截图之后发现是么得内容的, 于是乎查了一下API
preserveDrawingBuffer: 是否保留缓冲区数据, 如果你需要读取像素,或者复用绘制到主屏幕上的图像 ( 实现脏矩形局部刷新 ) , 需要开启这个, 否则浏览器在发生新的绘制操作的时候, 有可能清空以前的数据
就是在获取webgl对象的时候,多传入一个{preserveDrawingBuffer: true}
, 然后在使用canvas.toDataURL()获取就能够获取到了
const gl = canvas.getContext('webgl',{preserveDrawingBuffer:true});
// 渲染一帧视频
loadTexture(gl, n, texture, u_Sampler, video);
console.log(canvas.toDataURL())
const image = document.createElement('img');
image.src = canvas.toDataURL();
document.body.append(image);
贴上一个 stackoverflow 上面的答案(自备翻译):
As I understand, preserveDrawingBuffer=true means WebGL has to flush the pipeline between frames. OpenGL drawing isn’t synchronous, and so drawing commands can be still in the pipeline when you finish your frame.
preserveDrawingBuffer = true
意味着 WebGL 必须刷新帧之间的管道. OpenGL 绘图不是同步的,因此当您完成帧时,绘图命令可能仍在管道中。
This would be equivalent to placing a flush at the end of your render loop. https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/flush
这相当于在渲染循环的末尾放置一个flush. https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/flush
So that is why the results can vary a lot. If your GPU has buffered a lot of commands, then it will then the program will be forced to stop while all the GPU commands are executed. However, if your GPU is fast, then there might not be much in the buffer, and so things simply continue.
所以这就是结果可能会有很大差异的原因。如果您的 GPU 缓冲了很多命令,那么在执行所有 GPU 命令时,程序将被迫停止。但是,如果您的 GPU 速度很快,则缓冲区中可能没有太多内容,因此事情会继续进行。
I’ve seen cases where placing a flush call at the end of the render loop dropped the Fps by 50%.
我见过在渲染循环结束时进行刷新调用会使 Fps 降低 50% 的情况。
I would avoid preserveDrawingBuffer=true because it will hurt performance when you need it most.
我会避免,
preserveDrawingBuffer=true
因为它会在你最需要的时候损害性能。