← Back to index

Dot product as projection

The dot product a·b measures how much of b lies along a. Divide by |a| and you get the signed projection length; positive when b points the same way as a, negative when it points the other way, and zero when they're perpendicular.

See also: Closest point on a line segment and Perpendicular distance from a point to a line — both built on this projection.

Pseudocode

dot = a.x * b.x + a.y * b.y
projectionLength = dot / |a|                 // signed
projectionVector = a * (dot / (a . a))

Source

const ox = 150, oy = 150
const ax = 100, ay = 0                       // vector a, fixed
const bx = mouseX - ox
const by = mouseY - oy

const dot = ax * bx + ay * by
const aLenSq = ax * ax + ay * ay
const projLen = dot / Math.sqrt(aLenSq)      // signed
const t = dot / aLenSq                       // parameter along a
const projX = ax * t
const projY = ay * t