如何在保留内容的情况下调整 WebGLTexture 的大小?

How can I resize WebGLTexture with keeping content?

我想调整通过绑定前一帧的帧缓冲区渲染的 WebGLTexture 的大小。

我尝试使用具有新大小的 texImage2D 调整此纹理的大小并保持格式和类型。

我知道这行不通。这可能会为整个像素生成大小为 [0,0,0,0] 的新纹理。

如何在保持内容的情况下调整 WebGLTexture 的大小?

您无法在 WebGL 中调整纹理大小而不丢失其内容。您需要分配另一个具有所需大小的纹理并将旧纹理的数据复制到它。有两种方法可以做到这一点:通过 copyTexSubImage2D 调用或通过绘制调用。请注意,第一种方法需要将旧纹理链接到帧缓冲区,而第二种方法 - 新纹理。

假设您的 WebGL 上下文是 gl,旧纹理是 oldTexture,它链接到的帧缓冲区是 oldFramebuffer,新纹理是 newTexture 及其帧缓冲区是 newFramebuffer.

使用 copyTexSubImage2D 你可以这样做:

gl.bindFramebuffer(gl.FRAMEBUFFER, oldFramebuffer);
gl.bindTexture(gl.TEXTURE_2D, oldTexture);
gl.copyTexSubImage2D(
    gl.TEXTTURE_2D,
    0,
    offsetInNewTextureX,
    offsetInNewTextureY,
    offsetInOldTextureX,
    offsetInOldTextureY,
    width,
    height
);

大功告成!请注意,此方法不允许您操作纹理数据,只是将其逐像素复制。

第二种方法有点复杂,需要一些我不会在这里列出的着色器。基本上,您需要设置上下文以绘制带纹理的四边形。

gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, oldTexture);
gl.uniform1i(shaderTextureUniformLocation, 0);

gl.bindFramebuffer(gl.FRAMEBUFFER, newFramebuffer);
gl.drawArrays(/* ... */); // Draw the quad.

这样您还可以操作复制的数据,即拉伸它。

I tried to resize this texture using texImage2D with new size and keeping formats and type.

I know this wont work. This maybe generate new texture with the size cleared with [0,0,0,0] for entire pixels.

是的,你就在这里。