如何在 webGL 的特定位置将一个纹理写入另一个纹理?

How do I write one texture onto another at a specific location in webGL?

我想做一些看起来很简单的事情,但我是 webgl 的新手,很难找到一个教程来简单地做到这一点。假设我有两个 webgl 纹理准备好与我的 webgl2 渲染上下文一起使用。我只想在坐标 x, y 处将 texture1 写到 texture2 上。设置它的准系统方法是什么?

从一个纹理渲染到另一个纹理需要将要写入的纹理(目标纹理)附加到帧缓冲区

const fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb):
const attachmentPoint = gl.COLOR_ATTACHMENT0;
const textureType = gl.TEXTURE_2D;
const mipLevel = 0;  // must be 0 on WebGL1
gl.framebufferTexture2D(gl.FRAMEBUFFER, attachmentPoint, 
                        textureType, someTexture, mipLevel);

然后渲染到纹理使用

gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.viewport(0, 0, widthOfTexture, heightOfTexture);

再次渲染到 canvas 使用

gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

https://webglfundamentals.org/webgl/lessons/webgl-render-to-texture.html

请注意,在 WebGL1 中,只有一种格式的纹理可以保证可以渲染。 internalFormat = gl.RGBA,格式 = gl.RGBA,类型 = gl.UNSIGNED_BYTE。在 WebGL2 中有一个 table。请参阅 reference guide

的第 5 页

否则,渲染到 canvas 与渲染到纹理之间没有区别。将某些东西渲染到 canvas 上的特定位置的方式与渲染到纹理上的特定位置的方式完全相同。您设置几何体、属性、制服,根据要绘制的对象的大小进行任何所需的数学运算,然后进行绘制。如果您不知道该怎么做 this article shows code that renders a rectangle. This article shows how to render something at any position. This article shows how to use matrices to be more flexible

渲染源纹理与将一些纹理 triangles/geometry/etc 渲染到 canvas 没有什么不同。您在着色器中声明一个统一采样器,将纹理绑定到纹理单元并进行绘制。 This article shows how to use textures

This article combines all of those lessons to draw a textured quad anywhere using any portion of a texture.