Get all pixel coordinates between 2 points

后端 未结 3 1260
我寻月下人不归
我寻月下人不归 2021-02-04 13:20

I want to get all the x,y coordinates between 2 given points, on a straight line. While this seems like such an easy task, I can\'t seem to get my head around it.

So, fo

3条回答
  •  北恋
    北恋 (楼主)
    2021-02-04 14:11

    Edit: The solution below only applies from a geometrical point of view. Drawing on a screen is different than theoretical geometry, you should listen to the people suggesting Bresenham's algorithm.


    Given, two points, and knowing that the line's equation is y = m*x + b, where m is the slope and b the intercept, you can calculate m and b and then apply the equation to all the values of the X axis between your A and B points:

    var A = [10, 5];
    var B = [15, 90];
    
    function slope(a, b) {
        if (a[0] == b[0]) {
            return null;
        }
    
        return (b[1] - a[1]) / (b[0] - a[0]);
    }
    
    function intercept(point, slope) {
        if (slope === null) {
            // vertical line
            return point[0];
        }
    
        return point[1] - slope * point[0];
    }
    
    var m = slope(A, B);
    var b = intercept(A, m);
    
    var coordinates = [];
    for (var x = A[0]; x <= B[0]; x++) {
        var y = m * x + b;
        coordinates.push([x, y]);
    }
    
    console.log(coordinates); // [[10, 5], [11, 22], [12, 39], [13, 56], [14, 73], [15, 90]]
    

提交回复
热议问题