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

  • By
    Serving Fonts from CDN

    For maximum performance, we all know we must put our assets on CDN (another domain).  Along with those assets are custom web fonts.  Unfortunately custom web fonts via CDN (or any cross-domain font request) don't work in Firefox or Internet Explorer (correctly so, by spec) though...

  • By
    Camera and Video Control with HTML5

    Client-side APIs on mobile and desktop devices are quickly providing the same APIs.  Of course our mobile devices got access to some of these APIs first, but those APIs are slowly making their way to the desktop.  One of those APIs is the getUserMedia API...

Incredible Demos

Discussion

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