Jaap
Jaap

Reputation: 169

html5 canvas use image as mask

Is it possible to use a image with a shape as a mask for a whole canvas or images within the canvas?

I want to place images in a canvas with a mask over the images, and then save it as a new image.

Upvotes: 9

Views: 13202

Answers (2)

m90
m90

Reputation: 11822

In addition to Pierre's answer you can also use a black and white image as a mask source for your image by copying its data into a CanvasPixelArray like:

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);

Upvotes: 1

Pierre
Pierre

Reputation: 1282

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

Your final image will only be draw where it overlay 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); 

More info on global composite operations

Upvotes: 18

Related Questions