WebGL drawing 2d objects with different blending modes

1.6k views Asked by At

I am trying to figure out how to do blending modes in WebGL. Until now, I used the native HTML5 Canvas drawing functions, with which you can just do, for instance:

var ctx = new Document.getElementById('canvas').getContext('2d');
ctx.globalCompositeOperation = 'lighter'

Now, I am trying, for performance reasons, to port this to WebGL. However, I have trouble understanding the way I can influence the blending mode in WebGL. As I understood it, a Vertex shader decides what pieces of different textures/polygons are visible, and the fragment shader is then called for each pixel of the visible part of these textures/polygons. However, if I have a blending mode such as lighter (which takes the higher one of each of the components of the underlying colour and the new overlaying colour), I get confused about the role the vertex shader and the fragment shader have in this case.

Even further, in the Pixi.js library I am using to draw with WebGL right now I believe the vertex and fragment shaders are only called after all objects have been drawn to the framebuffer, in other words: only after all objects are placed. (The shaders this library uses can be found here)

Could someone explain how to properly use blending modes in WebGL?

1

There are 1 answers

1
Dragan Okanovic On BEST ANSWER

Vertex shader positions all vertices in drawing space and, if needed, passes certaing varying variables to the fragment shader.

Fragment shader is where all the calculations about final color of the pixel/fragment are done.

So where does blending come into place?

When rendering the scene, there are final color buffer (framebuffer) and depth buffer (renderbuffer). Color buffer holds the RGBA value for some fragment at (x,y) position on the screen, and depth buffer holds the depth value for that same fragment.

If blending is not active, then if some fragment has the same (x,y) position, first the depth components will be compared (current pixel vs one from depth buffer), and if currently rendered fragment is closer to camera, its color would overwrite the one already written in the color buffer, otherwise both buffers would remain untouched.

If blending is on, than the part of the color buffer will be changed one way or another, and how it would be changed depends on the equation that is used for blending. There are many different blending modes and equations that can be used, you just adjust them to your needs.

Useful links:

Hope this helps.