Last active
April 19, 2023 06:12
-
-
Save LapysDev/46108ce0b18218bf36c37f282e910355 to your computer and use it in GitHub Desktop.
〰️ Line-to-Coordinates: Algorithm to draw a line between two coordinates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
draw_line(x1, x2, y1, y2) { | |
x = 0, y = 0; // where each pixel of the line is drawn | |
xLength = abs(x1 - x2), yLength = abs(y1 - y2); | |
xRatio = 1, yRatio = 1; // Asserts how the line is weighted between the x and y axis | |
if (xLength > yLength) yRatio = yLength / xLength; | |
else if (xLength < yLength) xRatio = xLength / yLength; | |
// draw the line | |
xIterator = 0; // for progressing through the iteration | |
yIterator = 0; // based on the ratios of x and y separately | |
while ((x + x1) < x2 && (y + y1) < y2) { | |
xIterator += xRatio; | |
yIterator += yRatio; | |
draw_pixel(x, y); | |
// when x becomes 1 (due to x:1 relationship with y), then update the x coordinate at which we draw the line | |
// same principle for y | |
if (xIterator >= 1) { x1 > x2 ? --x : ++x; --xIterator; } | |
if (yIterator >= 1) { y1 > y2 ? --y : ++y; --yIterator; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment