Search code examples
htmlcanvasmask

Mask a canvas with image


This is the situation: I need to do a "splatter" effect to show the content behind (be it a body background image, or a google map). I'm thinking of overlaying a canvas on top of the actual content. The canvas will have an opaque (white) background initially. Then, I'll mask it with the splatter images and interval to show the underlying content.

I've found this fiddle that does something similar: http://jsfiddle.net/VqCbv/43/ However, the mask is drawn with fillRec and createLinearGradient Can I modify the code somehow to use an actual image for the mask, for a more flexible shape?

Thanks in advance.


Solution

  • All you need to do is to first create and load in an image with the "splatter". Then you set composition mode of the canvas to destination-out and simply draw the image on top of your canvas:

    ctx.globalCompositeOperation = 'destination-out';
    ctx.drawImage(img, 0, 0);
    

    What will happen is that all pixels that are in the image will remove the pixels on the canvas leaving the area the image was in as a transparent area. The other pixels (the white) will be intact.

    Demonstration (click canvas to splatter):
    http://jsfiddle.net/AbdiasSoftware/4A4Qv/

    As you can see a hole is punched in the canvas so the background is visible.