html5 canvas使用图像作为掩码

时间:2012-10-01 12:45:01

标签: javascript html5 canvas

是否可以使用带有形状的图像作为整个画布的掩模或画布中的图像?

我想将图像放在带有遮罩的画布上,然后将其保存为新图像。

2 个答案:

答案 0 :(得分:13)

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

您的最终图像只会在覆盖蒙版的地方绘制。

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

答案 1 :(得分: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);