Using HTML5 Canvas for Image Masks
Recently I’ve found myself referring to Jake‘s (the bastard legend that is) HTML5 Video with alpha transparency demo for reference into some pixel manipulation techniques with Canvas. Used in a slightly different context, but largely the same technique, we can use Canvas to apply a full alpha mask to any image element.
For Webkit browsers, a similar effect can be used with CSS Masks, but perhaps you need slightly wider browser support, or you want to use the masked image in Canvas somewhere else.
This function is just a base and should really be tailored to your use case, but it shows how easy it is to read the alpha data from one image, and apply it to another. Using getImageData, a 4-chunk CanvasPixelArray is returned with each pixels’ R, G, B, and A values. The result is achieved reading and ‘merging’ the RGB values from the base image, and the A values from the mask.
That’s all it does, but having it wrapped up into a single function is sometimes easier to work with (again, depending on your use case). The function creates a couple of Canvas elements on the DOM and uses them to mash the pixels together. You just pass in the base and mask images, and get back the single masked image either as a CanvasPixelArray, or as a Base-64 encoded data URL.
To give you an idea of what the images can be, here are the raw images I’m using for the utterly useless demo.
- Base JPEG: http://playground.benbarnett.net/canvas-mask/img/octagon.jpg
- Mask PNG-24: http://playground.benbarnett.net/canvas-mask/img/alpha.png
Feel free to head over to the Github repo for further docs.Tweet Follow @benpbarnett