Canvas Filters

By  on  

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!

Recent Features

Incredible Demos

  • By
    Making the Firefox Logo from HTML

    When each new t-shirt means staving off laundry for yet another day, swag quickly becomes the most coveted perk at any tech company. Mozilla WebDev had pretty much everything going for it: brilliant people, interesting problems, awesome office. Everything except a t-shirt. That had to change. The basic...

  • By
    Telephone Link Protocol

    We've always been able to create links with protocols other than the usual HTTP, like mailto, skype, irc ,and more;  they're an excellent convenience to visitors.  With mobile phone browsers having become infinitely more usable, we can now extend that convenience to phone numbers: The tel...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!