2012-10-01 89 views
5

是否可以将具有形状的图像用作画布内整个画布或图像的蒙版?html5 canvas使用图像作为蒙版

我想将图像置于画布上,并在画布上放置图像,然后将其保存为新图像。

+0

是,如果在遮罩图像上确实存在透明区域,则可以使用'drawImage()'在画布顶部绘制图像。透明部分将让底层图像/画布闪耀。 – devnull69

+0

这不是我的意思,我希望形状可以剪切图像,以便图像的其余部分变得透明。 – Jaap

回答

9

您可以使用'source-in'globalCompositeOperation将黑白图像用作蒙版。首先将遮罩图像绘制到画布上,然后将globalCompositeOperation更改为“源代码”,最后绘制最终图像。

您的最终图像只能在覆盖面具的地方绘制。

var ctx = document.getElementById('c').getContext('2d'); 

ctx.drawImage(YOUR_MASK, 0, 0); 
ctx.globalCompositeOperation = 'source-in'; 
ctx.drawImage(YOUR_IMAGE, 0 , 0); 

More info on global composite operations

+0

它部分工作,当我添加更多的图片到画布失败。我如何正确设置蒙版,所以当我加载更多的图像时,它仍然使用蒙版? – Jaap

+0

将globalCompositeOperation设置回绘图后最初的状态(很可能是“源代码”)。 –

1

除了皮埃尔的回答,你也可以使用一个黑白图像作为图像掩码源通过复制其数据到CanvasPixelArray,如:

var 
dimensions = {width: XXX, height: XXX}, //your dimensions 
imageObj = document.getElementById('#image'), //select image for RGB 
maskObj = document.getElementById('#mask'), //select B/W-mask 
image = imageObj.getImageData(0, 0, dimensions.width, dimensions.height), 
alphaData = maskObj.getImageData(0, 0, dimensions.width, dimensions.height).data; //this is a canvas pixel array 

for (var i = 3, len = image.data.length; i < len; i = i + 4) { 

    image.data[i] = alphaData[i-1]; //copies blue channel of BW mask into A channel of the image 

} 

//displayCtx is the 2d drawing context of your canvas 
displayCtx.putImageData(image, 0, 0, 0, 0, dimensions.width, dimensions.height); 
+3

不幸的是,像素旁路并不像drawImage方法那样高效。 –