Bresenham\'s Line Algorithm


/ Published in: JavaScript
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. function calcStraightLine (startCoordinates, endCoordinates) {
  2. var coordinatesArray = new Array();
  3. // Translate coordinates
  4. var x1 = startCoordinates.left;
  5. var y1 = startCoordinates.top;
  6. var x2 = endCoordinates.left;
  7. var y2 = endCoordinates.top;
  8. // Define differences and error check
  9. var dx = Math.abs(x2 - x1);
  10. var dy = Math.abs(y2 - y1);
  11. var sx = (x1 < x2) ? 1 : -1;
  12. var sy = (y1 < y2) ? 1 : -1;
  13. var err = dx - dy;
  14. // Set first coordinates
  15. coordinatesArray.push(new Coordinates(y1, x1));
  16. // Main loop
  17. while (!((x1 == x2) && (y1 == y2))) {
  18. var e2 = err << 1;
  19. if (e2 > -dy) {
  20. err -= dy;
  21. x1 += sx;
  22. }
  23. if (e2 < dx) {
  24. err += dx;
  25. y1 += sy;
  26. }
  27. // Set coordinates
  28. coordinatesArray.push(new Coordinates(y1, x1));
  29. }
  30. // Return the result
  31. return coordinatesArray;
  32. }

URL: http://stackoverflow.com/questions/4672279/bresenham-algorithm-in-javascript

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.