Published
Edited
Sep 16, 2019
1 star
Insert cell
Insert cell
function drawLine(imageData, points) {
function setPoint(x, y) {
// console.log(x, y);
const i = Math.round(y) * imageData.width * 4 + Math.round(x) * 4;
imageData.data[i] = 255;
imageData.data[i + 1] = 255;
imageData.data[i + 2] = 255;
imageData.data[i + 3] = 255;
}

const [[x1, y1], [x2, y2]] =
points[0][1] < points[1][1] ? points : [points[1], points[0]]; // order by first y-point
// console.log(x1, y1, x2, y2);

// Special case to avoid divide by zero
if (x1 === x2) {
for (let y = y1; y <= y2; y++) {
setPoint(x1, y);
}
return imageData;
}

// Special case to avoid divide by zero
if (y1 === y2) {
for (let x = Math.min(x1, x2); x <= Math.max(x1, x2); x++) {
setPoint(x, y1);
}
return imageData;
}
// Two Point Form of the Linear Equation:
// (y1 - y2) * x + (x2 - x1) * y + (x1 * y2 - x2 * y1) = 0
// Slope is rise over run:
// m = (y2 - y1) / (x2 - x1)
// The y intercept is when x = 0:
// y0 = (x2 * y1 - x1 * y2) / (x2 - x1)

// Then we plot using the Slope-Intercept form:
// y = m * x + y0
// Also: x = (y - y0) / m
const m = (y2 - y1) / (x2 - x1);
// console.log('m = ', m);
const y0 = (x2 * y1 - x1 * y2) / (x2 - x1);
// console.log('y0 = ', y0);

let x;
for (let y = y1, x_calc = x1; y <= y2; y++, x_calc = x) {
x = (y - y0) / m;
const max = Math.max(x_calc, x);
for (x_calc = Math.min(x_calc, x); x_calc <= max; x_calc++) {
setPoint(x_calc, m * x_calc + y0);
}
}
return imageData;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more