I’m trying to set a transparent background for a shader, but I don’t know how. if the canvas has a background color or background image / video it works fine, but if it is transparent the “shader” is completely black.
precision highp float;
uniform float time;
uniform vec2 resolution;
uniform sampler2D texture;
varying vec2 vUv;
const float duration = 8.0;
const float delay = 4.0;
#pragma glslify: random = require(./random);
void main() {
float now = clamp((time - delay) / duration, 0.0, 1.0);
float whiteNoise = random(vUv.xy * time) * 0.1 - 0.1;
float monitor1 = abs(sin(vUv.y * resolution.y * 2.4 + time * 10.0)) * 0.04;
float monitor2 = abs(sin(vUv.y * resolution.y * 1.0 + time * 3.0)) * 0.04;
float monitor = monitor1 - monitor2;
vec4 color = vec4((texture2D(texture, vUv).rgb + whiteNoise) + monitor, 1.0);
gl_FragColor = color;
}
i tried to add
if (color.a <0.1) discard;
but it only works for opacity parameter vec4 (1.0)
If anyone knows or can help with advice, that would be awesome!
- You technically don’t need to discard a fragment - the effect will be similar if you just set
color.a
to 0.0
.
- To have any kind of opacity effects, be sure to set
transparent: true
on the material.
- Your discarding might not have worked because you always set
color.a
(the last parameter) to 1.0:
vec4 color = vec4((texture2D(texture, vUv).rgb + whiteNoise) + monitor, 1.0);
color.a
stands for alpha
channel, which defines the transparency of the color - if you set it to value lower than 1.0
you should start seeing transparency. And if your texture already has transparent pixels, you can just do:
vec4 textureImage = texture2D(texture, vUv);
vec4 color = vec4((textureImage.rgb + whiteNoise) + monitor, textureImage.a);
1 Like
vec4 textureImage = texture2D(texture, vUv);
vec4 color = vec4((textureImage.rgb + whiteNoise) + monitor, textureImage.a);
Now it is completely transparent. Coz scene has no texture / background and
const renderer = new THREE.WebGLRenderer({
canvas: canvas,
alpha: true,
clearColor: 0x000000,
clearAlpha: 0,
});
but if I try
vec4 color = vec4(whiteNoise + monitor, 1.0);
it is returns an error