Given two points you can find the slope of a line by the following equation:
Where m represents the slope and (x_1,y_1) represents the x and y component of the first point and (x_2,y_2) represents the x and y component of the second point.
Once we obtain the slope we can then use the point-slope equation to find the equation of a line:
For example, if we have the points (1,6) and (3,2) and want to find the slope we can calculate it as shown below:
Now we can use either the point (1,6) or the point (3,2) and our slope m = -2 to find the equation of a line using the point slope formula:
Simplifying further we obtain:
Now, why did we go through all of this hard work? Well, we only need two points to describe a line. However, there are an infinite amount of points that exist on our line.Therefore we can use the equation of a line that we found above to determine whether a point exists on our line.
So for example, if we wanna determine whether the point (2,4) exists on our line we can plug in x = 2 and y = 4 into our equation above and we find the following:
Simplifying we obtain:
Therefore we know that the point (2,4) exists on our line!
However, this idea works for finding points between two points. The math used above is the same math used in a very efficient algorithm mentioned below which finds what we are looking for.
I would encourage that you take a look at an algorithm called Bresenham’s line algorithm as this is a fast algorithm for calculating exactly what you desire. The algorithm avoids messy calculations such as avoiding floating-point arithmetic and unnecessary steps.
In the algorithm, we are essentially moving along the x-axis and looking to determine whether we should draw our pixel’s y-unit above or draw our pixel’s y-unit below and we’re repeating this process until we reach our desired endpoint.
Some key differences are that the slope must be positive and must have an absolute value of less than one. The algorithm also assumes that the change of x (meaning the difference between our endpoint’s x value and our initial point’s x value) can never be zero to avoid a 0 in the denominator.
You could try to implement this algorithm and create a table where you will then insert the coordinates of the pixels from your initial point to the endpoint.
I hope this could be of some use! I’m interested in reading the other replies to this thread, to see if there is an easier way to perform this task.