Javascript displacement mapping

| 2 min read

I wrote a javascript displacement map filter, mostly as an experiment, this graphic technique has been widely used in Flash.

Check out the following demos:

Displacement mapping is a simple action of shifting pixels. An image map containing color values is used as data to create the displacement and move pixels around.

The filter can be used several different effects, here are some that have been done in Flash, these might give you ideas:

And two great links to have a better understanding of the displacement mapping. Both links explain the Flash version of the filter, but it is almost identical (missing modes for now) to the one I wrote in javascript. I strongly recommend to read the first link.

About the demo with the picture, I created an image map in Photoshop, please notice my skill with a brush :)

displacement map

I used the javascript displacement filter to apply it on the following picture, and finally draw it in a canvas. photo

The filter itself will take different parameters that can be changed in real-time (on a time interval): - a canvas containing the image on which the filter will be applied on - a canvas containing the image map to create the displacement - a canvas where the result will be drawn - a point (x and y) where the displacement will be applied on the image source - a scale value for the X axis, this will be the amount of displacement on this axis - a scale value for the Y axis - a color channel for the X axis, the color used to create the displacement on this axis - a color channel for the Y axis

It will look like this:

var filter = new filters.DisplacementMap(
new filters.Point(50, 50),

When the draw method is called, the filter will loop over the pixels of the image map and find the color that has been specified to create the displacement. A color is represented by the hexadecimal value of 255 (0xFF). If the color found in the map for a specific pixel is superior to the half (0x80), the pixel shifting will increase, otherwise it will decrease.

About the second demo, I reproduced a flash demo from Zeh Fernando that I really liked. There's a simple background with heart pattern used as a source image, and the displacement map looks like this: displacement map

The gradient colors are chosen so that the displacement will create a magnifying effect. The red colors will be used to move the pixels on the X axis and the green colors will be used to move on the Y axis.

I also reproduced a little trick to emphasis the displacement. Ive added a simple png with transparency on top of the displacement, it contains lights and shadows: heart

I also tweened the filter values with TweenJS to add a bit of movement (the heart bump), as in the Flash version.

Click here to download the demo and source.