簡體   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