2012-10-01 86 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方法那樣高效。 –