Bresenham's Line Drawing Algorithm
Bresenham's line algorithm is a line drawing algorithm that determines the points of an n-dimensional
raster that should be selected in order to form a close approximation to a straight
line between two points. It is commonly used to draw line primitives in a bitmap
image (e.g. on a computer screen), as it uses only integer addition,
subtraction and bit shifting, all of which are very cheap operations in
standard computer architectures. It is an incremental error algorithm. It is
one of the earliest algorithms developed in the field of computer graphics. An
extension to the original algorithm may be used for drawing circles.
Below is an implementation of Bresenham's Line Drawing Algorithm.
Library used: p5.js
Web Editor: https://editor.p5js.org
Output Screenshots:
Code:
var numCol;
var numRow;
var xStart, yStart, xEnd, yEnd;
var x1, x2, y1, y2;
x1 = 2;
y1 = 1;
x2 = 7;
y2 = 3;
//drawing
xStart = x1, yStart = y1;
xEnd = x1, yEnd = y1;
function setup() {
createCanvas(500, 500);
background(0);
numCol = 10;
numRow = 10;
unitX = width / numCol;
unitY = height / numRow;
//initializing the drawing
xStart *= unitX;
yStart *= unitY;
xEnd *= unitX;
yEnd *= unitY;
while (xStart < x2 * unitX) {
refPointX = xStart + unitX;
refPointY = yStart + (0.5 * unitY);
refPointPos = checkSign(refPointX, refPointY);
console.log(refPointX, refPointY);
console.log(refPointPos);
if (refPointPos < 0) {
//East
xEnd += unitX;
stroke(255);
strokeWeight(5);
line(xStart, yStart, xEnd, yEnd);
xStart += unitX;
yEnd += unitY;
line(xStart, yStart, xEnd, yEnd);
yStart = yEnd;
} else {
//SouthEast
stroke(255);
strokeWeight(5);
xEnd += unitX;
line(xStart, yStart, xEnd, yEnd);
xStart = xEnd;
}
}
}
function draw() {
stroke(25);
drawGrid();
drawRefLine();
}
function drawGrid() {
strokeWeight(1);
for (var i = 1; i < numCol; i++) {
line(unitX * i, 0, unitX * i, height);
line(0, unitY * i, width, unitY * i);
}
}
function drawRefLine() {
strokeWeight(1);
stroke(180);
line(x1 * unitX, y1 * unitY, x2 * unitX, y2 * unitY);
}
function checkSign(x, y) {
m = (y2 - y1) / (x2 - x1);
c = y1 - (m * x1);
c *= unitX;
f = y - (m * x) - c;
return f;
}
No comments:
Post a Comment