xxxxxxxxxx
58
// BresenhamLine
const blockSize = 40
function setup() {
createCanvas(400, 400)
}
function draw() {
strokeWeight(1)
stroke(0)
fill(255, 0, 0)
for (let x = 0; x < width; x += blockSize) {
for (let y = 0; y < width; y += blockSize) {
rect(x, y, blockSize, blockSize)
}
}
fill(0)
BresenhamLine(1 * blockSize, 1 * blockSize, 5 * blockSize, 1 * blockSize)
}
function BresenhamLine(x0, y0, x1, y1) {
const deltaX = x1 - x0
const deltaY = y1 - y0
const deltaErr = abs(deltaY / deltaX)
let error = 0.0
let y = y0
for (let x = x0; x < x1; x += blockSize) {
// fill line
noStroke()
rect(x, y, blockSize, blockSize)
// draw mid point
const midBlockX = x + blockSize * 0.5
const midBlockY = y + blockSize * 0.5
stroke(255, 255, 255)
strokeWeight(4)
point(midBlockX, midBlockY)
error += deltaErr
if (error > 0.5) {
y = y + Math.sign(y) * blockSize
error = error - 1.0
}
}
}