要创建输出纹理,我需要调用texImage2D吗?

时间:2018-08-28 13:15:33

标签: webgl webgl2

在Webgl中,我目前进行以下调用以创建纹理,无论该纹理用于输入还是用于输出。知道我的着色器将覆盖纹理中的值时,真的需要调用texImage2D吗?

const texture = gl.createTexture();
// Bind the texture so the following methods effect this texture.
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

gl.texImage2D(
    gl.TEXTURE_2D,
    0,  // Level of detail.
    this.encoder.internalFormat, width, height,
    0,  // Always 0 in OpenGL ES.
    this.encoder.format, this.encoder.channelType, null);
this.checkError();
gl.bindTexture(gl.TEXTURE_2D, null);
return texture as WebGLTexture;

1 个答案:

答案 0 :(得分:0)

这是一个完整的代码示例,它将创建与画布大小相同的纹理(可用于屏幕外渲染)

const gl = canvas.getContext('webgl');
const fb = gl.createFramebuffer();

const texture = gl.createTexture();

gl.bindTexture(gl.TEXTURE_2D, texture);

gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.canvas.width, gl.canvas.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);

gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);

您以后可以使用渲染的纹理,或使用gl.readPixels读取其内容