Use html5 canvas image as mask

Can I use an image with a shape as a mask for the entire canvas or images inside the canvas?

I want to place images on a canvas using a mask on images, and then save it as a new image.

+5
source share
2 answers

You can use a black and white image as a mask using the 'source-in' globalCompositeOperation. First you draw a mask image on the canvas, then you change globalCompositeOperation to "source", finally, you draw your final image.

Your last image will only draw where it overlays the mask.

var ctx = document.getElementById('c').getContext('2d');

ctx.drawImage(YOUR_MASK, 0, 0);
ctx.globalCompositeOperation = 'source-in';
ctx.drawImage(YOUR_IMAGE, 0 , 0); 

Additional Information on Global Compound Operations

+10

- , 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);
+1

All Articles