Clipping and masking images in CSS with mask-image

OCTOBER 7, 2022

Some time ago, I tried the mask-image CSS property.

You can use this property with SVG or PNG masks to mask a web element (say, a div or an img tag) and hide certain parts. You can use CSS gradients and patterns as well.

There are different blending modes. I wondered if we could use a black and white mask, or if we needed to have an alpha channel. And it turns out mask-mode: luminance allows me to use JPEG black and white images as alpha masks instead of saving them as PNG with an actual alpha transparency channel.

What does this allow me to do?

Well, with a bit of extra work for each drawing I publish on my site, I can export two alpha masks in JPEG format, where white represents visible areas and black hidden ones.

I export one mask for the actual drawing, appending the -mask.jpg suffix at the end of the filename, and another one for the text labels and lines outside of the main drawing, with the -mask-white.jpg suffix.

This way, I have three files: edit, mask, and mask-white, containing the actual drawing image, a mask for the main drawing, and a mask for the labels and external lines, respectively.

I've been following this process with all my drawings for years, so I have a high-resolution repository of images exported this way. When support for mask-image is browser-wide, including Chrome and other modern browsers, I'll play with this to better support dark mode and enable special interactions1.

You can read more about mask-image and its browser compatibility.

  1. I've experimented with an idea to fade or completely hide drawing annotations and text and display them on hover or as the drawing focuses.