MiJyn MiJyn - 1 year ago 70
Javascript Question

canvas clearrect, with alpha

So I know that

makes pixels transparent, but I'm wondering, is there a function to make pixels translucent?

For example, say I have a canvas with these colors (fourth one in each color is alpha):

#ffff #feef #abff
#5f6f #000f #ffff

would resolve into this (or something, just make them all transparent):

#fff0 #fee0 #abf0
#5f60 #0000 #fff0

I want to remove opacity, but not make it transparent (kind of like
), so that it can end up like this (lets say I set the
equivalent to 0.5):

#fff8 #fee8 #abf8
#5f68 #0008 #fff8

Is this possible? Or would it be simpler just to draw everything on an off-screen canvas, then draw that canvas (with
set) on an on-screen one?

Let me know if this isn't clear in any way.

Answer Source

I just tried to figure this out too, and I've decided to count through the pixels, setting the alpha channel of each one manually. This is a bit more work, because I can't just cover the entire canvas with a rect, but it's working so far.

I'm doing this so that I can set a background image for the webpage and put my canvas animation over it, without having to draw the background in the canvas element.

var oldArray = context.getImageData(0,0,canvas.width,canvas.height);
//count through only the alpha pixels
for(var d=3;d<oldArray.data.length;d+=4){
    //dim it with some feedback, I'm using .9
    oldArray.data[d] = Math.floor(oldArray.data[d]*.9);