HTML5 Canvas to PNG zeroes all channels when alpha

2019-05-10 15:46发布

问题:

I have a Uint32Array I am trying to convert to a texture for WebGL. To do this I'm writing the array as RGBA values on a Canvas and getting a base64 encoded PNG from the canvas to send as a texture.

Whenever I set a pixel value to have an alpha of 0, the corresponding RGB channels are also zeroed upon conversion to a PNG. Is this an implementation detail? If I were to create PNGs in some other non-HTML5 program could I have an (RGBA) quadruplet of (255,255,255,0)? I tried using an alpha value of 1 and all other channels remain intact, so this is not an issue of premultiplied alpha.

Here is some javascript code to reproduce this effect:

    var img = new Image();
    var canvasObj = $('<canvas width="1" height="1"></canvas>');
    var context = canvasObj[0].getContext('2d');
    var imgd = context.getImageData(0,0,1,1);
    var pix = imgd.data;
    pix[0]=255; pix[1]=255; pix[2]=255; pix[3]=0;
    context.putImageData(imgd,0,0);
    img.src = canvasObj[0].toDataURL("image/png");

    context.drawImage(img,0,0);
    var imgd2 = context.getImageData(0,0,1,1);
    var pix2 = imgd2.data;

pix2 will be all 0s.

Thanks!

回答1:

It appears to be part of the PNG specification (http://www.libpng.org/pub/png/spec/1.2/png-1.2-pdg.html).

...fully transparent pixels should all be assigned the same color value for best compression.

I couldn't find a direct source, but it seems like this particular implementation sets all the channels to zero.