Linear interpolation between two points. The mouse position is projected onto the line to derive t, which is then clamped to [0, 1] so the result stays on the segment.
See also: Closest point on a line segment — same projection, framed around distance instead of t.
x = ax + (bx - ax) * t
y = ay + (by - ay) * t
const ax = 40, ay = 240
const bx = 260, by = 60
// project mouse onto the line a->b to get t
const abx = bx - ax
const aby = by - ay
const apx = mouseX - ax
const apy = mouseY - ay
let t = (apx * abx + apy * aby) / (abx * abx + aby * aby)
t = Math.max(0, Math.min(1, t)) // clamp to segment
const x = ax + (bx - ax) * t
const y = ay + (by - ay) * t