|
| 1 | + |
| 2 | +'use strict'; |
| 3 | + |
| 4 | +/** |
| 5 | + * The Bresenham Algorithm, implemented in JS. |
| 6 | + * Learn more here: http://en.wikipedia.org/wiki/Bresenham's_line_algorithm |
| 7 | + * @author Evan Jacobs <evan@evoked.us> |
| 8 | +
|
| 9 | + * The loop calculates each pairing and returns them as an array of comma-separated |
| 10 | + string coordinates to be applied to a SVG (polyline) or canvas object. |
| 11 | +
|
| 12 | + * @param {Number} x1 - start point x |
| 13 | + * @param {Number} y1 - start point y |
| 14 | + * @param {Number} x2 - end point x |
| 15 | + * @param {Number} y2 - end point y |
| 16 | + * @param {Boolean} debug - set to true to get function timing in your console |
| 17 | +
|
| 18 | + * @returns {Array} point coordinates in "x,y" format |
| 19 | + */ |
| 20 | + |
| 21 | +function bresenham_line( x1, y1, x2, y2, debug ){ |
| 22 | + |
| 23 | + /* |
| 24 | + Points to be saved in comma-separated string pairs |
| 25 | + e.g. "41,0" for "x,y" |
| 26 | + */ |
| 27 | + |
| 28 | + if(debug) console.time('bresenham_line'); |
| 29 | + |
| 30 | + var points = []; |
| 31 | + |
| 32 | + var dx = Math.abs( x2 - x1 ); |
| 33 | + var dy = Math.abs( y2 - y1 ); |
| 34 | + |
| 35 | + var err = 0; |
| 36 | + var derr = Math.abs( dy / dx ); |
| 37 | + |
| 38 | + var y = y1; |
| 39 | + |
| 40 | + for( var x = x1, end = x2; x < end; x++ ){ |
| 41 | + |
| 42 | + // Add coordinate string to array (includes x1,y1 by default) |
| 43 | + points.push( [x,y].join(',') ); |
| 44 | + |
| 45 | + err += derr; |
| 46 | + |
| 47 | + if( err >= 0.5 ){ |
| 48 | + y += 1; |
| 49 | + err -= 1; |
| 50 | + } |
| 51 | + |
| 52 | + } |
| 53 | + |
| 54 | + // Finally, add on the last set |
| 55 | + points.push( [x2,y2].join(',') ); |
| 56 | + |
| 57 | + if(debug) console.timeEnd('bresenham_line'); |
| 58 | + |
| 59 | + return points; |
| 60 | +} |
| 61 | + |
| 62 | +/* |
| 63 | +
|
| 64 | + Example usage: |
| 65 | +
|
| 66 | + var points = bresenham_line( 0, 0, 10, 10 ); |
| 67 | +
|
| 68 | + points => ["0,0", "1,1", "2,2", "3,3", "4,4", "5,5", "6,6", "7,7", "8,8", "9,9", "10,10"] |
| 69 | +
|
| 70 | + This could then be used in an SVG polyline like this: |
| 71 | + $('<svg>').append('<polyline points="' + points.join(' ') + '" />'); |
| 72 | +
|
| 73 | +*/ |
0 commit comments