I recently unearthed an old Java applet that I had written many years ago and decided to see what it would look like as a single page canvas application (an HTML5 compatible browser is required to view this page). The applet was inspired by the way blackbirds roost on power lines in San Francisco (and probably everywhere else). I started with something close to Craig Reynold’s classic Boids algorithm, which is remarkable for generating motion resembling a flock of birds by giving each particle only 3 relatively simple mathematical constraints. I had to add 6 more rules to incorporate the power line behavior (2 for landing, 1 for hopping on the line, and 3 for launching off the line).
The rules are:
Since the application is only required to draw simple circles and lines, there was little opportunity to explore features of the canvas API. Most of the code is devoted to the calculations. JavaScript isn’t great at handling all the vector math. I tried to write it in a more functional style, but the additional object creation and function calls required to do immutable math turned out to make a pretty significant increase in CPU usage, so I replaced some each calls with for loops and tried to minimize the need to generate 3D point objects. I could have eliminated the points altogether and run the calculations on each coordinate separately, but the performance boost wouldn’t be worth the mess it would make in the code.
Feel free to view the source and use what you like. I’ve been doing a lot of canvas work that I’ll be posting about here soon.
Alex is Carbon Five's resident mad genius. He is recently very involved in functional languages, and has been anchoring teams at C5 for the past decade.