The WEBGL_draw_buffers
extension is part of the WebGL API and enables a fragment shader to write to several textures, which is useful for deferred shading, for example.
WebGL extensions are available using the WebGLRenderingContext.getExtension()
method. For more information, see also Using Extensions in the WebGL tutorial.
Note: This extension is only available to WebGL1 contexts. In WebGL2, the functionality of this extension is available on the WebGL2 context by default. In WebGL 2, the constants are available without the "WEBGL" suffix and the new GLSL built-ins require GLSL #version 300 es
.
This extension exposes one new method.
ext.drawBuffersWEBGL()
-
Defines the draw buffers to which all fragment colors are written. (When using WebGL2
, this method is available as gl.drawBuffers()
by default).
Enabling the extension:
const ext = gl.getExtension("WEBGL_draw_buffers");
Binding multiple textures (to a tx[]
array) to different framebuffer color attachments:
const fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
ext.COLOR_ATTACHMENT0_WEBGL,
gl.TEXTURE_2D,
tx[0],
0,
);
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
ext.COLOR_ATTACHMENT1_WEBGL,
gl.TEXTURE_2D,
tx[1],
0,
);
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
ext.COLOR_ATTACHMENT2_WEBGL,
gl.TEXTURE_2D,
tx[2],
0,
);
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
ext.COLOR_ATTACHMENT3_WEBGL,
gl.TEXTURE_2D,
tx[3],
0,
);
Mapping the color attachments to draw buffer slots that the fragment shader will write to using gl_FragData
:
ext.drawBuffersWEBGL([
ext.COLOR_ATTACHMENT0_WEBGL,
ext.COLOR_ATTACHMENT1_WEBGL,
ext.COLOR_ATTACHMENT2_WEBGL,
ext.COLOR_ATTACHMENT3_WEBGL,
]);
Shader code that writes to multiple textures:
<script type="x-shader/x-fragment">
#extension GL_EXT_draw_buffers : require
precision highp float;
void main(void) {
gl_FragData[0] = vec4(0.25);
gl_FragData[1] = vec4(0.5);
gl_FragData[2] = vec4(0.75);
gl_FragData[3] = vec4(1.0);
}
</script>