1
votes

I'm trying to render some graphics with transparency into a WebGLRenderTarget. The rendered image is then used as texture for a second material.

I have an issue with alpha blending. The color that I obtain when alpha=0.5 is darker than expected.

The image below shows the issue:

Top: DIV with opacity=0.5; Bottom: WebGL

  • Circle on top is what I expect. This is obtained with an HTML DIV with rounder corners and opacity=0.5
  • Circle on bottom is what I obtain with with a shader that renders the circle inside a texture.

I think that I'm missing something!

Part of the code is reported below. You can find the complete code in the following jsbin: https://jsbin.com/zukoyaziqe/1/edit?html,js,output

Thank you for your help!!

Shader:

const texFrag = `
varying vec2 vUv;
void main() {
  vec2 center = vec2(0.5, 0.2);
  float d = length(vUv - center);

  if (d < 0.1) {
    gl_FragColor = vec4(1.0,0.0,1.0,0.5);
  }
  else {
    discard;
  }
}
`;

Texture:

const makeTexture = (renderer, width, height) => {
  const target   = new THREE.WebGLRenderTarget(width, height, {minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat, type: THREE.FloatType});
  const scene    = new THREE.Scene();
  const camera   = new THREE.PerspectiveCamera(90, 1, 0.1, 100000);
  const geometry = new THREE.PlaneGeometry(2, 2);
  const material = new THREE.ShaderMaterial({
    transparent    : true,
    vertexShader   : simpleVert,
    fragmentShader : texFrag,
  });
  const mesh = new THREE.Mesh(geometry, material);

  camera.position.set(0, 0, 1);
  scene.add(camera);
  scene.add(mesh);

  renderer.render(scene, camera, target, true);

  return target.texture;
}

Main view:

const renderer = new THREE.WebGLRenderer({canvas});
const scene    = new THREE.Scene();
const camera   = new THREE.PerspectiveCamera(90, 1, 0.1, 100000);
const geometry = new THREE.PlaneGeometry( 2, 2 );
const material = new THREE.MeshBasicMaterial({
  transparent : true,
  map         : makeTexture(renderer, canvas.width, canvas.height)
});
const mesh = new THREE.Mesh(geometry, material);
1

1 Answers

1
votes

First of all, in the example you linked, your main function is called twice, so there are two CSS circles stacked on top of each other, resulting in a less transparent circle.

Then, you're drawing a circle with color (1,0,1,0.5) on a blank render target, which, using the default blend mode (SRC_ALPHA, ONE_MINUS_SRC_ALPHA), results in (0.5,0,0.5,0.5) color, which is then used as a texture. If you want the original color in your texture, you should disable alpha blending or use a different blend mode. Simply setting transparent to false inside makeTexture does the trick.