Danny Fox
Danny Fox

Reputation: 40709

How to set half-transparent color in webgl?

I red this tutorial about object colors: http://learningwebgl.com/blog/?p=134

This code will create a red square:

squareVertexColorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexColorBuffer);
colors = []
for (var i=0; i < 4; i++) {
  colors = colors.concat([1.0, 0.0, 0.0, 1.0]);
}
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);

it works, but if I modify the code to this:

colors = colors.concat([1.0, 0.0, 0.0, 0.5]);

then the object isn't half transparent, it's pink. I dont know, why is it pink. The object color should be between green, and pink, because of the green background:

gl.clearColor(0.0, 1.0, 0.0, 1.0);
gl.enable(gl.DEPTH_TEST);

Upvotes: 1

Views: 1923

Answers (1)

Toji
Toji

Reputation: 34498

It sounds like you may not have blending enabled. Try adding the following lines in your initialization code:

gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE);

And see if you get different results. The blend mode may not be exactly what you want, but it should at least show you if it's working.

For a more in-depth breakdown of blending, check out Learning WebGL Lesson 8.

Upvotes: 2

Related Questions