ctown4life
ctown4life

Reputation: 965

Combining two images on one canvas in HTML5

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.

Upvotes: 5

Views: 12275

Answers (1)

C-Mo
C-Mo

Reputation: 1192

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.

Upvotes: 7

Related Questions