Threejs Shader - gl_FragColor with Alpha (opacity

2019-06-25 10:27发布

问题:

I'm trying to write a simple shader where half of my scene will be displayed and half of the scene will be transparent. I can't seem to figure out why the transparency isn't working:

  uniform sampler2D tDiffuse;
  varying vec2 vUv;

  void main(){
        vec2 p = vUv;
        vec4 color;      

        if(p.x < 0.5){ 
              color = (1.0, 0.0, 0.0, 0.0);
        }else{
              color = texture2D(tDiffuse, p);
        }

        gl_FragColor = color;
  }

The shader is definitely running without errors - the right half of the screen is my threejs scene and the left half of the screen is red (when it should really be transparent). I've read that maybe I need to call glBlendFunc(GL_SRC_ALPHA); - but I am getting errors when I try this. To do this I did renderer.context.blendFuncSeparate(GL_SRC_ALPHA); in my main js file (not the shader). Am I supposed to place this somewhere else to make it work?

Any help would be appreciated. For reference I'm applying my shader with the standard effectsComposer, shaderPass, etc - which most threejs shader examples use.

Thanks in advance for your help!!!

回答1:

It is difficult to help you with only partial information and code snippets, so I can only make educated guesses.

By default EffectComposer uses a render target with RGB format. Did specify RGBA?

Did you specify material.transparent = true?

three.js r.56