scriptNode

Web development with a focus on JavaScript RSS

Bresenham’s Line Algorithm In JavaScript

Intermediate Matt Hackett Published July 6th, 2008 by Matt Hackett

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 the setInterval call uses [default: 10]
  • onComplete: An optional function to call when the algorithm is finished
  • speed: 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!

Read other articles tagged: , , ,

Comments (2)

  • Unknown user

    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.

  • Unknown user

    Good post.

Thoughts?

(required)

© 2009 scriptNode