Web DevelopmentJavaScript Paint


Working with bitmaps is fundamental to graphical programs such as games. Well, it's possible to manipulate bitmaps in JavaScript too! Obviously we can work with arrays of data in JavaScript, so we have no problem representing the bitmap data. The only problem is displaying this data as a bitmap image. Well, we certainly don't want to be creating divs for each pixel, so what can we do? The answer is to make use of Data URIs.

Data URIs have been around for quite some time, but browser support is still limited. They allow you to define the data that a URI will return directly in the URI itself, and thus there's no server involved at all. The browser reads the URI, interprets the data and displays it accordingly. As such you can directly specify an image's content from within your page's HTML itself.

The obvious next step is to directly manipulate the data URI for an image with client side JavaScript code. JavaScript directly editing a bitmap, live! If we pad this out with a bit of interface to respond to what you do with your mouse then we've got Paint! The only problem is that updating the bitmap data and recalculating the corresponding data URI is going to be somewhat processor intensive. If we only have one thread then when we're doing this recalculation we can't be dealing with the user's mouse events, causing the smooth lines to come out jerky. But making use of a web worker to do this hard work the UI can continue on smoothly, unaffected.

I'll explain below a bit more about how it works at a later date, but for now, putting it all together, this is what you get...

If your browser supports data URIs (IE 8 for instance) then it should be fully functional. If it also supports Web Workers (Firefox 3.5), then it should run that bit smoother. Unfortunately only Firefox supports passing JSON messages between workers, other browsers only support passing string messages, so for now, in those browsers I'm not using native Web Workers either.

Obviously there are improvements that can be made and bugs to fix, but for now, enjoy your doodling! Oh, and if you do create a masterpiece and wish to save it then you can do this by choosing the cursor tool and right clicking on you picture, the usual image context menu including a save option should be available.