Bresenham&039;s线算法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Bresenham&039;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.
  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. }

以上是关于Bresenham&039;s线算法的主要内容,如果未能解决你的问题,请参考以下文章

Bresenham画线算法

用C++如何实现bresenham画线算法?计算机图形学上面有个drawpixel的函数。不知道怎么用。

Bresenham 线算法。文件是不是存在 ncurses 输出?

Bresenham 线算法错误

Bresenham 线算法所有情况

Bresenham画线算法详解及其OpenGL编程实现