Bresenham’s Line Algorithm In JavaScript
Today for Script Sunday I implemented Bresenham's line algorithm in the web browser. If you've got JavaScript enabled, you should see a red square in the upper-left hand corner of the box below. Clicking anywhere within the box should send the square to that location.
Here's the source code:
The parameters are self-explanatory except for the (optional) params object. Here's a breakdown:
delay: The interval that thesetIntervalcall uses [default: 10]onComplete: An optional function to call when the algorithm is finishedspeed: How quickly to move the element down the line [default: 5]
I'm not sure how much use this has in the "real world" but it's typically pretty neat to see elements dancing around the page, and I always love to see classic algorithms put to good use. Enjoy!
- [Download bresenhams-line-algorithm.js] (1,769 bytes)
- [Download bresenhams-line-algorithm-min.js] (516 bytes; compressed)
Cool! This takes me back. I wrote something like this a few years back, but ended up hacking the heck out of it to try to make it remember starting positions, and then giving up and using Flash.
In your version, the more vertical the line is, the faster the box moves; also, lots of clicking eventually seems to break it. And a purely vertical click to the bottom left corner does nothing at all; which makes sense, because the original algorithm has to have x!=0, otherwise it’s dividing by 0.
The increasing/decreasing speed behavior based on slope is fascinating. There has to be some kind of use for that.
Good post.