Created
January 24, 2022 16:41
-
-
Save loleg/07941cd8aa6a23eeb056cb30d5ae7d2b to your computer and use it in GitHub Desktop.
The simplest line drawing algorithm
This file contains hidden or 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
/* | |
* @name DDA graphics algorithm | |
* @description A simple implementation of line rasterization using the Digital differential analyzer. | |
* Press the mouse button on any two points to draw a line. A color will be picked at random. | |
* See https://en.wikipedia.org/wiki/Digital_differential_analyzer_(graphics_algorithm) | |
*/ | |
let i = x1 = y1 = x2 = y2 = dx = dy = step = 0; | |
let pickStart = pickEnd = false; | |
function reset() { | |
i = x1 = y1 = x2 = y2 = 0; | |
pickStart = false; | |
pickEnd = false; | |
} | |
function setup() { | |
createCanvas(720, 400); | |
colorMode(HSB, 100); | |
background(230); | |
strokeWeight(1); | |
frameRate(30); | |
} | |
function draw() { | |
if (mouseIsPressed) { | |
// Make sure the clicks are far enough apart | |
if (pickStart && !pickEnd && | |
abs(mouseX - x1) > 10 && | |
abs(mouseY - y1) > 10) { | |
x2 = mouseX; | |
y2 = mouseY; | |
pickEnd = true; | |
startDDA(); | |
// Don't abort the line draw too soon | |
} else if (i == 0 || i > 10) { | |
reset(); | |
x1 = mouseX; | |
y1 = mouseY; | |
pickStart = true; | |
} | |
} | |
if (pickStart && pickEnd) { | |
runDDA(); | |
} | |
} | |
function startDDA() { | |
// Show destination | |
stroke(137, 134, 193); | |
strokeWeight(2); | |
point(x2, y2); | |
// Pick line color at random | |
stroke(random(50), 93, 93); | |
// DDA algorithm | |
dx = (x2 - x1); | |
dy = (y2 - y1); | |
if (abs(dx) >= abs(dy)) | |
step = abs(dx); | |
else | |
step = abs(dy); | |
dx = dx / step; | |
dy = dy / step; | |
x = x1; | |
y = y1; | |
} | |
function runDDA() { | |
// Pick current point | |
strokeWeight(2); | |
point(x, y); | |
// Continue iteration | |
x = x + dx; | |
y = y + dy; | |
i = i + 1; | |
if (i > step) { | |
reset(); | |
return; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment