WebGL Canvas Background-Color visible when using Alpha Blending

Posted on:November 29 2012

I was just working on some rendering code of CopperLicht, the WebgL backend for CopperCube, and noticed a very strange behavior. Somehow, all the transparent elements in the scene looked somehow colored. Playing around with it, I suddenly realized that the color depends on the used background color of the canvas element in the HTML (For an upcoming new feature, you will be able to define the HTML background color for the WebGL canvas in the editor). Setting the color back to its default, black, made it look ok again:

I suspected some strange thing going on somewhere in my shaders, maybe I was setting the background color somewhere erroneously? Or I was multiplying the loaded texture somehow with it somewhere? I was confused.
After searching for a while, nothing like this seemed to happen. The color somehow "shined through" from the background. Hm. Was this a bug in Chrome? I tried out Firefox. The same behavior there. Strange. Both browsers wouldn't have the same unusual bug, would they? So it must have been be a feature. Somehow.
Well, after looking through the WebGL specs, I finally found out that this actually is a feature: It looks like WebGL has alpha destination operations for the canvas turned on by default. Useful for compositing stuff, but probably not what the average WebGL-Canvas programmer is expecting, I guess. At least not me :) You can turn this default to false when getting the canvas context, by using a line like this:

var gl = canvas.getContext("webgl", {alpha: false} );

Which fixes this issue. So maybe this is a usueful blog post for another programmer who also stumbles across this problem. :)

Add comment:

Posted by:

Enter the missing letter in: "Inter?ational"




Possible Codes

Feature Code
Link [url] www.example.com [/url]
Bold [b]bold text[/b]
Quote [quote]quoted text[/quote]
Code [code]source code[/code]