Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 961
Jaap Avatar asked Oct 01 '12 12:10

Jaap


People also ask

How do you make a mask on canvas?

Method 1 - Using composite mode to clip /// draw the shape we want to use for clipping ctx1. drawImage(imgClip, 0, 0); /// change composite mode to use that shape ctx1. globalCompositeOperation = 'source-in'; /// draw the image to be clipped ctx1. drawImage(img, 0, 0);

How do you mask a picture?

Quick steps for creating a clipping mask: Select a text or graphic layer to fill with an image. Click Fill with image on the tool palette & choose an image. Select Edit image fill on the Text Tools panel. Adjust the image behind your text or shapes, then click Done.

How do I add a mask to an image in CSS?

The mask-image CSS property sets the image that is used as mask layer for an element. By default this means the alpha channel of the mask image will be multiplied with the alpha channel of the element. This can be controlled with the mask-mode property.

Does HTML5 support canvas element?

The canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D shapes and bitmap images.


2 Answers

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

like image 73
Pierre Avatar answered Oct 08 '22 01:10

Pierre


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);
like image 28
m90 Avatar answered Oct 08 '22 02:10

m90