Christian Heilmann

Image masking with HTML5 Canvas

Saturday, June 15th, 2013 at 10:24 am

I just added a small demo to my GitHub showing how you can do image masking by using the canvas element.

masks

All you need to do is add the canvasmask.js script and add a class of mask to each image you want to mask. You also need to provide a PNG file as the mask using the data-mask attribute. For example:

<img src="red-panda.jpg" 
     alt="Red panda" 
     class="mask" 
     data-mask="centerblur.png">

This will take the centerblur.png file and apply it as a mask to red-panda.jpg – in effect taking the alpha of each pixel and change the alpha of the original pixel to that.

You can see it in action here and get the code on GitHub.

Under the hood, all I do is loop through all the pixels of the images (after copying them to two canvas elements) and apply the alpha values (every 4th value in the pixeldata array) of the PNG to the image. Simple, really :)

As mentioned by Jake Archibald on Twitter there is no need to loop over the pixels of the images, all you need is to copy the mask first, then change the canvas compositing to source-atop and add the image. Done. The script does that now, and thus is much faster.

Share on Mastodon (needs instance)

Share on Twitter

Newsletter

Check out the Dev Digest Newsletter I write every week for WeAreDevelopers. Latest issues:

160: Graphs and RAGs explained and VS Code extension hacks Graphs and RAG explained, how AI is reshaping UI and work, how to efficiently use Cursor, VS Code extensions security issues.
159: AI pipelines, 10x faster TypeScript, How to interview How to use LLMs to help you write code and how much electricity does that use? Is your API secure? 10x faster TypeScript thanks to Go!
158: 🕹️ Super Mario AI 🔑 API keys in LLMs 🤙🏾 Vibe Coding Why is AI playing Super Mario? How is hallucinating the least of our worries and what are rules for developing Safety Critical Code?
157: CUDA in Python, Gemini Code Assist and back-dooring LLMs We met with a CUDA expert from NVIDIA about the future of hardware, we look at how AI fails and how to play pong on 140 browser tabs.
156: Enterprise dead, all about Bluesky and React moves on! Learn about Bluesky as a platform, how to build a React App and how to speed up SQL. And play an impossible game in the browser.

My other work: