In a WebGL I'd like to send a screen space quad through that gets processed by a fragment shader, but have the fragment shader only write out a pixel under certain conditions (say... that it was within a circle, or that the pixel belonged to the positive side of a halfspace defined by a curve equation or something).

Is it possible within a fragment shader to say "don't write a pixel"?

I know this could be accomplished using various other methods like alpha blending, rendering this first and having it put the background color where it doesn't want to draw a pixel, or maybe doing some trick with the depth or stencil buffers. I also know i could create a bunch of geometry to match what it is that I want to render.

Is there a way though to make the fragment shader choose not to write a pixel at all?


2 Answers 2


Yes, you can discard in the fragment shader to avoid writing the pixel. Here's a random example I dug up from Google.

Note that this may not actually stop the fragment shader from processing (as the GPU tends to process fragments in blocks; only discarding from all fragments in a block will abandon the processing). But the fragment won't be written to the output, which is basically what you want.

You may be interested in this related question about the performance of discard and this one on SO.

I have no idea if this is supported in WebGL though. If it isn't, you'll need to fall back to one of your suggestions (like alpha blending; I think that would be the most straightforward).


The discard statement comes in handy.

You didn't say too much about your decision path, so I'll offer an example using a simple texture lookup:

void main() {
    gl_FragColor = texture2D(u_texture, v_uv) * u_color;
    if (gl_FragColor.a <= 0.0) discard;

(That's from some sample code I wrote before I learned about alpha blending.)


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .