繁体   English   中英

html5 canvas使用图像作为掩码

[英]html5 canvas use image as mask

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

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

您可以使用“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); 

有关全球复合运营的更多信息

除了皮埃尔的答案,您还可以使用黑白图像作为图像的蒙版源,方法是将其数据复制到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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM