是否可以将具有形状的图像用作整个画布或画布内图像的蒙版?
我想将图像放在带有蒙版的画布中,然后将其另存为新图像。
您可以使用'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);
除了 Pierre 的回答之外,您还可以通过将黑白图像的数据复制到 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);