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
    5 HTML5 APIs You Didn&#8217;t Know Existed

    When you say or read "HTML5", you half expect exotic dancers and unicorns to walk into the room to the tune of "I'm Sexy and I Know It."  Can you blame us though?  We watched the fundamental APIs stagnate for so long that a basic feature...

  • By
    How I Stopped WordPress Comment Spam

    I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database...

Incredible Demos

  • By
    Face Detection with jQuery

    I've always been intrigued by recognition software because I cannot imagine the logic that goes into all of the algorithms. Whether it's voice, face, or other types of detection, people look and sound so different, pictures are shot differently, and from different angles, I...

  • By
    Fading Links Using jQuery:  dwFadingLinks

    UPDATE: The jQuery website was down today which caused some issues with my example. I've made everything local and now the example works. Earlier this week, I posted a MooTools script that faded links to and from a color during the mouseover and mouseout events.

Discussion

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