JavaScript - how to add alphas of 2 images so the result is alpha = 1?

I need to make a transition between two images - both images are masks that hide a sprite bellow. Part of each mask is white, part is transparent. I need the total alpha of both images to be 1 every time so it looks like the mask smoothly changes its shape. If I use a transition of alpha from 1 to 0 for image1 and 0 to 1 for image2 and then draw both images over each other, then result isn't alpha1 + alpha2 = 1. Is there any way how to get it? Thanks a lot, Vaclav

Upvotes: 0

Views: 45

Answers (1)

Volune
Volune

Reputation: 4339

I think it's the default behaviour of the canvas, at the condition that the destination is the original image1 (not multiplied by alpha from 1 to 0).

The source-over operation does result = alpha*source + (1-alpha)*dest, even for the alpha channel.

I don't have mask images to test it, but I think this code should do what you want:

ctx.globalCompositeOperation = 'copy';
ctx.globalAlpha = 1.;
ctx.drawImage(img1, 0, 0);
ctx.globalCompositeOperation = 'source-over';
ctx.globalAlpha = ratio;
ctx.drawImage(img2, 0, 0);

(Some lines are unnecessary if you know in which state the context was before the computation)


(By the way, giving an example code to reproduce the problem in your question would be much appreciated)

Upvotes: 1

Related Questions