Implementing the Duotone Filter with an SVG Filter

In a recent post I described a duotone CSS Custom Filter I had built that allowed you to take a black and white image, and remap the black and white colors to two other specified colors.  Say you have a t-shirt website.  You could provide a single black and white image, and users could choose the color they want.

In the original implementation I used CSS Custom Filters, which are a little overkill for this use, and they are currently only supported on Chrome.  Here we’re going to do the same thing, using an SVG Filter.  SVG Filters are currently supported on both Chrome and Firefox and stand a much better chance of being implemented in other browsers sooner rather than later.

In particular, we’re going to use the ComponentTransfer filter primitive, described in more detail in this post.

Let’s take a look at the following SVG implementation (best viewed on Chrome and/or Firefox):

Check out this Pen!

When you click on either the black or white color remapping buttons, JavaScript is executed which recalculates the transfer functions for the feComponentTransfer filter primitives for each color channel.

In the following demo:

Check out this Pen!

We don’t use any JavaScript.  Instead, we’re using the SVG animate primitive to animate the table values of each transfer function (feFuncR, feFuncG, feFuncB).

For both of these examples, click on the HTML, CSS and JS tabs to see what’s going on and let me know if you have any questions.

As you can see, SVG filters are extremely powerful and worth learning more about.  Using them to manipulate HTML content is currently only supported on Chrome and Firefox but it looks very promising that they’ll be supported on all browsers before too long.

Tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *