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
    How to Create a RetroPie on Raspberry Pi &#8211; Graphical Guide

    Today we get to play amazing games on our super powered game consoles, PCs, VR headsets, and even mobile devices.  While I enjoy playing new games these days, I do long for the retro gaming systems I had when I was a kid: the original Nintendo...

  • By
    CSS Filters

    CSS filter support recently landed within WebKit nightlies. CSS filters provide a method for modifying the rendering of a basic DOM element, image, or video. CSS filters allow for blurring, warping, and modifying the color intensity of elements. Let's have...

Incredible Demos

  • By
    NSFW Blocker Using MooTools and CSS

    One of my guilty pleasures is scoping out the latest celebrity gossip from PerezHilton.com, DListed.com, and JoBlo.com. Unfortunately, these sites occasionally post NSFW pictures which makes checking these sites on lunch a huge gamble -- a trip to HR's office could be just a click away. Since...

  • By
    MooTools Zebra Table Plugin

    I released my first MooTools class over a year ago. It was a really minimalistic approach to zebra tables and a great first class to write. I took some time to update and improve the class. The XHTML You may have as many tables as...

Discussion

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