Badass JavaScript

A showcase of awesome JavaScript that pushes the boundaries of what's possible on the web, by @devongovett.

StackBlur: A Fast Gaussian Blur Algorithm In JavaScript

October 11th 2010

image

Mario Klingemann has created a fast implementation of an “almost gaussian blur algorithm” in JavaScript.

This is a compromise between Gaussian Blur and Box blur It creates much better looking blurs than Box Blur, but is 7x faster than my Gaussian Blur implementation. I called it Stack Blur because this describes best how this filter works internally: it creates a kind of moving stack (or maybe a “Tower of Hanoi” kind of structure) of colors whilst scanning through the image. This “tower” controls the weights of the single pixels within the convolution kernel and gives the pixel in the center the highest weight. The secret of the speed is that the algorithm just has to add one new pixel to the right side of the stack and at the same time remove the leftmost pixel. The remaining colors on the topmost layer of the stack are either added on or reduced by one, depending on if they are on the right or on the left side of the stack.

The original version of the algorithm was written in Processing, and there have been ports to other languages, but Mario decided that it was time to bring it to the canvas element as well.  The algorithm is fast enough that if you are on a modern browser (Chrome, Firefox 4 beta, etc.) the image can be updated in real time while you drag the slider controlling the amount of blur to apply.  Check it out, here!

Very neat!  It is with fast algorithms like this, and with fast JavaScript performance that we will be able to reproduce the effects that coders in the desktop and Flash world have had for a long time.  A JS version of Photoshop isn’t that far off!