js1k: an allRGB entry in <1k of JavaScript


It’s contest season! The An Event Apart 10k JavaScript app contest has just ended (my entry got 2/5), there’s a node.js contest, and the JS1k contest is ending on Sept 10th. JS1k is a much purer contest, disallowing any external libraries, while the 10k contest allowed things like jQuery and external web services. As Frederick Polgardy puts it, js1k is “An exercise in constraint, resulting in a kind of executable haiku”.

For js1k, I’ve entered a port of my PHP allRGB entry. The allRGB project is a great idea in itself – create an image which contains every possible colour in the RGB space exactly once. That’s 256*256*256 colours (=16777216), in a 4096×4096 image. Quite a challenge for PHP, and certainly not the kind of thing you’d attempt in JavaScript, right? ;D

The code itself is pretty simple stuff – three nested for loops and you’re basically done. A few little tweaks to make sure it runs fairly smoothly in all browsers. Unlike the PHP version you can’t really just set and forget, so I’m using setTimeout to break the task down into smaller chunks, which means the browser won’t trigger its “This script is running slowly” message. I also use window.scroll to show the user that something’s actually happening on screen.

As I mentioned, this isn’t the kind of thing you’d normally turn to JavaScript for, and it puts quite a strain on the browser. It’s very interesting to see how the different browsers fare. Opera is the fastest, followed closely by Chome, then Firefox. Safari puts on a generally poor show, being slow and having some rendering problems while the drawing/scrolling is happening, but it does work in the end. It doesn’t run in IE 8 or 9, I’ll probably have a look at that at some point, it’s bound to be be something silly.

The final minified code comes in at 713 bytes. I could get that down further for sure, but there’s no need to just yet.

Check out the demo here.

Here’s the original source. Leave a comment if you can spot the IE errors :)


Related Posts:

, , , , , ,

Comments are closed.