(JavaScript) Bresenham’s Line Algorithm

Code obtained from a [stackoverflow question](http://stackoverflow.com/questions/4672279/bresenham-algorithm-in-javascript). This is a javascript implementation of the [Bresenham line algorithm](http://en.wikipedia.org/wiki/Bresenham’s_line_algorithm).

Given two points, this function will return an array of coordinates which go from point A to point B, one step at a time.

  1.  
  • Posted by on January 1st, 1970
This entry was posted in JavaScript and tagged , , , , , . Bookmark the permalink. Trackbacks are closed, but you can post a comment.

2 Comments

  1. Emerson
    Posted April 28, 2013 at 9:02 pm | Permalink

    Thank you for sharing this. I’ve created a Lua version of it.

    function getLinePath(x1,y1,x2,y2)

    x1 = math.floor(x1)
    y1 = math.floor(y1)

    x2 = math.floor(x2)
    y2 = math.floor(y2)

    local dx = math.abs(x2 – x1);
    local dy = math.abs(y2 – y1);

    local sx = x1 < x2 and 1 or -1
    local sy = y1 -dy) then
    err = err – dy
    x1 = x1 + sx
    end

    if (e2 < dx) then
    err = err + dx
    y1 = y1 + sy
    end

    points[instance] = {x={}, y={}}
    points[instance].x = x1
    points[instance].y = y1

    instance = instance + 1
    end

    return points
    end

    • Emerson
      Posted April 28, 2013 at 9:10 pm | Permalink

      Your comment feature is messing out the code…here a escaped version of it.

      function getLinePath(x1,y1,x2,y2)

      x1 = math.floor(x1)
      y1 = math.floor(y1)

      x2 = math.floor(x2)
      y2 = math.floor(y2)

      local dx = math.abs(x2 – x1);
      local dy = math.abs(y2 – y1);

      local sx = x1 < x2 and 1 or -1
      local sy = y1 < y2 and 1 or -1

      local err = dx – dy

      local points = {x={}, y={}}

      local instance = 1

      while ((x1 ~= x2) and (y1 ~= y2)) do

      local e2

      e2 = err * 2

      if (e2 > -dy) then
      err = err – yd
      x1 = x1 + sx
      end

      if (e2 < dx) then
      err = err + dx
      y1 = y1 + sy
      end

      points[instance] = {x={}, y={}}
      points[instance].x = x1
      points[instance].y = y1

      instance = instance + 1
      end

      return points
      end

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?