← Back to index

2D cross product

In 2D the cross product is a single scalar, a.x·b.y − a.y·b.x. Its magnitude is the area of the parallelogram spanned by the two vectors, and its sign tells you whether b is to the left or right of a. It's the same number that drives triangle winding and the denominator in segment intersection.

See also: Triangle signed area — literally half this value.

Pseudocode

cross = a.x * b.y - a.y * b.x
// |cross| = area of the parallelogram spanned by a and b
// sign tells you the orientation (left/right turn)

Source

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

const cross = ax * by - ay * bx
const area  = Math.abs(cross)
const side  = cross > 0 ? 'right'      // remember: y points down on a canvas
          :   cross < 0 ? 'left'
          :                'collinear'