In a recent project, the graphic designer working in my same studio chose to apply a multiply filter on an image and to ask me to recreate the same effect on a HTML page.
Moreover, he decided that the multiply layer should fade out, showing the normal image if the user hovers the picture area.
How to do it: first way
The simplest way to obtain the live multiply effect would be to post-process each image and create two versions: the original one and another one with the multiply filter applied. This solution might be good, but:
- firstly, the editor should have uploaded two versions of the same image;
- secondly, the HTML page would have included two images of the same subject, so the end user would have been supposed to download both of them.
Second way: HTML5 canvas
Another possible solution to simulate the multiply effect on the page was to do it with HTML5 canvas. As the WHATWG says:
“The canvas element provides scripts with a resolution-dependent bitmap canvas, which can be used for rendering graphs, game graphics, or other visual images on the fly.”
Thanks to the canvas APIs I was able to get the color values of each pixel of the image and transform them applying the multiply formula, which simply is:
Color = (Top Color) * (Bottom Color) / 255
What about the browser’s support? Well, all modern browsers support the HTML canvas.
So, with IE 6-8 and other legacy browsers we can fall back to an element positioned above with the CSS
opacity value set less than one.
Canvas multiply filter
In order to obtain the filter, first of all I have added an
<canvas> before the image:
To manipulate the pixels, the canvas 2D Context API provides you three methods:
The first method,
createImageData, is used to clone the image on the canvas:
The second one,
getImageData, retrieves the color of each pixel of a determinate area and, after manipulating them, it lets you substitute the pixels using
multiplyColor variable is an array of RGB values; the
multiply function is a method that returns the computed color value, by applying the multiply formula.
Demo and final thoughts
If you want to see the canvas multiply filter in action, have a look at this demo.
At the moment the code accepts as “top level” only a single color, so the multiply filter is between an image and a spot. But it is not so hard to replace the single color with a gradient or another image.