Canvas Filters
Adding filters to images can make them more eye-catching and shareable -- just ask Instagram, Snapchat, Prism, and every other app out there. A few years back we got the awesome CSS filters feature, allowing us to use a fixed set of filter methods to make our photos beautiful. Of course CSS filters work on standard HTML elements, not just images, but images provide a better illustration of filter effects.
I was happy to see that browsers have recently implemented those same filters for <canvas>
element contents. Let's start with a snippet from my JavaScript Canvas Image Conversion post, converting an image to canvas:
// Converts image to canvas; returns new canvas element function convertImageToCanvas(image) { var canvas = document.createElement("canvas"); canvas.width = image.width; canvas.height = image.height; canvas.getContext("2d").drawImage(image, 0, 0); return canvas; } var canvas = convertImageToCanvas(document.querySelector('img'));
With a <canvas>
element ready, we can then implement CSS filters whenever we'd like:
canvas.getContext('2d').filter = 'blur(5px) opacity(0.6)';
You can see a full list of filters on MDN. I'm pleased that an API that started with CSS has been mirrored within canvas!