Last updated Sept. 11, 2022
In computer graphics classes you are presented with some line drawing algorithms. Examples of such are:
The Digital Differential Analyzer algorithm(DDA) is the simplest algorithm to implement as it draws the line incrementally by generating points from start to finish. The points are interpolated from the difference in start and end points. The current points are calculated from the previous points.
In this tutorial, we'll be using python language to implement the algorithm. For that we'll need a python package known as matplotlib which can be installed via the python package manager pip with the following command:
pip install matplotlib
Matplotlib will enable us to plot the points generated by the algorithm on the screen.
The following is the code for the algorithm:
import matplotlib.pyplot as plt
print("Enter the value of x1: ")
x1 = int(input())
print("Enter the value of x2: ")
x2 = int(input())
print("Enter the value of y1: ")
y1 = int(input())
print("Enter the value of y2: ")
y2 = int(input())
dx = x2 - x1
dy = y2 - y1
if abs(dx) > abs(dy):
steps = abs(dx)
else:
steps = abs(dy)
xincrement = dx/steps
yincrement = dy/steps
i = 0
xcoordinates = []
ycoordinates = []
while i < steps:
i +=1
x1 = x1 + xincrement
y1 = y1 + yincrement
print("X1: ",x1, "Y1: ", y1)
xcoordinates.append(x1)
ycoordinates.append(y1)
plt.plot(xcoordinates, ycoordinates)
#Naming the Axis
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
#Graph title
plt.title("DDA Algorithm")
#show the plot
plt.show()
You can also watch the instructions below:
Python, Django, Javascript
By subscribing, you will get one email every month on tips, tutorials, and resources to improve your skills as a developer. You will get early access to my courses and videos and also access to special bonus of the time. No spam, unsubscribe at any time