newbie keeps losing alpha values in canvas

2019-08-22 04:37发布

问题:

I'm probably doing something boneheaded here but I'm having difficulties getting alpha values to cooperate in Canvas. I'm trying to sample an opaque color from a spot on the canvas, make it more transparent, and lay it down in another spot -- but the alpha part doesn't seem to be working. Stripped down it goes sort of like this (condensed from functions strewn across the script):

p = ground.ctx.getImageData(loc.x, loc.y, 1, 1).data; 
col = {R: p[0], G: p[1], B: p[2], a: p[3]};
col.a = col.a - 0.1;
ground.ctx.fillStyle = 'rgba(' + col.R + ', ' + col.G + ', ' + col.B + ', ' + col.a + ')';
ground.ctx.fillRect(nuLoc.x, nuLoc.y, sqrSize, sqrSize);

It all runs, but when I test the value of fillStyle I get just a standard RGB "#fa674c" or whatever -- no mention of any alpha -- and when I getImageData() from the newly drawn Rect the value is fully opaque again.

Another thing I haven't been able to figure out either empirically or by reading every tutorial (and the spec) is whether alpha wants to be 0-1.0 or 0-255. Most sources talk about 0-1.0 -- but getImageData() returns 0-255... and I can't make it work either way.

回答1:

Use context.globalAlpha instead of using rgba fill:

p = ground.ctx.getImageData(loc.x, loc.y, 1, 1).data; 
col = {R: p[0], G: p[1], B: p[2], a: p[3]};

// note: globalAlpha uses a scale of 0-1
// and getImageData uses a scale of 0-255
ground.ctx.globalAlpha = a/255-.1;

ground.ctx.fillStyle = 'rgb(' + col.R + ', ' + col.G + ', ' + col.B + ')';
ground.ctx.fillRect(nuLoc.x, nuLoc.y, sqrSize, sqrSize);

// reset globalAlpha when you're done
ground.ctx.globalAlpha = 1;