javascript 在 HTML5 中的一个画布上组合两个图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3878319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Combining two images on one canvas in HTML5
提问by ctown4life
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.
我正在使用 HTML5 画布元素。假设我有 2 个 ImageData 对象,我想将它们组合起来放在一个画布上。让我们假设我不在乎这些图像如何组合。两个 ImageData 对象具有完全相同的像素数和形状。
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.
我想我可以编写一个 for 循环并遍历 ImageData 数组并手动组合和设置每个像素的每个 rgba 值,但我想知道是否有更好的方法?我需要尽快执行此操作。
Thanks in advance.
提前致谢。
回答by C-Mo
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.
这可能比通过 get/putImageData 方法逐像素绘制要快,尽管多少取决于浏览器。

