views:

38

answers:

1

I'm working with the HTML5 canvas element. Let's say I have 2 ImageData objects that I want to combine to be able to put on one canvas. Lets assume that I don't care how these images combine. Both ImageData objects have the exact same pixel count and shape.

What's the best way to combine the two images?

I figure that I can write a for loop and iterate over the ImageData array and manually combine and set every rgba value per pixel, but I'm wondering if there's a better way? I need this operation to happen as quickly as possible.

Thanks in advance.

+1  A: 

If you're simply looking to superimpose one image on top of another, you probably want to do something like this:

ctx.drawImage(image1, x, y);
// adjust globalAlpha as needed, or skip if the image has its own transparency
ctx.globalAlpha = 0.5;
ctx.drawImage(image2, x, y);

OR, depending on the specific effect you're after:

ctx.drawImage(image1, x, y);
ctx.globalCompositeOperation = "lighten"; // many other possibilities here
ctx.drawImage(image2, x, y);

This will probably be faster than drawing pixel-by-pixel through the get/putImageData methods, though by how much is browser-dependent.

C-Mo
The questioner said (in a later comment) that the image pixels are mostly transparent, so I don't think the alpha or compositing operation even need to be set.
andrewmu
That's correct. I'll update the comment in the first set of code.
C-Mo