在HTML5中将两个图片合并在一个画布上 [英] Combining two images on one canvas in HTML5

查看:1235
本文介绍了在HTML5中将两个图片合并在一个画布上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用HTML5 canvas元素。假设我有2个ImageData对象,我想要组合在一个画布上。让我们假设我不在乎这些图像如何组合。两个ImageData对象具有完全相同的像素数和形状。



这两个图像的最佳组合方式是什么?



我想,我可以写一个for循环和迭代的ImageData数组,手动合并和设置每个像素的每个rgba值,但我想知道是否有一个更好的方法?

解决方案



如果你只是想把一个图像叠加在另一个图像上,你可能想这样做:

  ctx.drawImage(image1,x,y); 
//根据需要调整globalAlpha,如果图像有自己的透明度,则跳过
ctx.globalAlpha = 0.5;
ctx.drawImage(image2,x,y);

或,取决于您之后的具体效果:

  ctx.drawImage(image1,x,y); 
ctx.globalCompositeOperation =lighten; //其他许多可能性
ctx.drawImage(image2,x,y);

这可能比通过get / putImageData方法逐像素绘制更快,多少依赖于浏览器。


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.

解决方案

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.

这篇关于在HTML5中将两个图片合并在一个画布上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆