JavaScript Library - WebGL-2D animation not working


I found a nifty JavaScript library that allows for "hardware accelerated" canvas 2d drawing: https://github.com/corbanbrook/webgl-2d

I tried the example out and the first frame renders like it should, but after the first frame, the canvas is white.

I setup a fiddle here: http://jsfiddle.net/RaW5x/5/

I have to assume it is the library because this is the example from the repository.

Short answer: I don't think it's the library's fault, but it is definitely an issue that the library should resolve.

Specifically, webgl-2d sets the GL color mask during initialization using gl.colorMask(1, 1, 1, 0) -- thus blocking any writes to the alpha channel.

Now, I must admit that I'm not entirely sure what's happening to turn the screen white. The blend function is (src alpha, one minus src alpha), which means that for every color written out, it will be blended with the background color according to the source alpha component. To simplify the explanation, here's the formula for just the Red channel:

Red = Rs * As + Rd * (1 - As)

...where Rs is the source (new) Red channel, As is the source Alpha channel, and Rd is the destination (current background) Red channel.

So, if we assume a Red color of 50 (or ~0.196 in WebGL), my understanding is that what should be happening is:

Red = 0.196 * 1 + 0.196 * (1 - 1) = 0.196

In other words, it should be replacing the previous color with the new one.

As long as the source channel equals the destination channel, even where alpha other than 1.0 is involved, the numbers change a bit, but not the result:

Red = 0.196 * 0.5 + 0.196 * (1 - 0.5) = 0.196

The result would obviously change if the destination Red channel is, in fact, different from the source channel, but even then I don't see how it works out to a white color. If the issue were due solely to blending, I would expect an incremental step towards white based on the value in the Alpha channel, not a "jump" to white in a single frame.

So mathematically, it looks fine to me. But, I can reproduce this issue in my own WebGL framework (Jax) by setting the color mask to prevent alpha writes, so it's not completely the fault of the library. My guess is this could be a bug in the OpenGL drivers on your and my (and countless other) machines.

I will continue to research this issue, and update this answer if I can learn anything.

Regardless, the problem can be resolved within the webgl-2d library. I have submitted a pull request to the developer. (FYI, the repo you linked in the question was a fork from the original repository; I can't tell who the current maintainer is so I sent the pull request to the original repository.)

Until the pull request is (hopefully) accepted, or the issue is otherwise resolved, I believe you can do this:

ctxGL.colorMask(1, 1, 1, 1);

...before doing any rendering, and it should Just Work.