pxToNdc

View sourcepxToNdc(x: number, y: number, width?: number, height?: number): Vector2

Converts a pixel-space coordinate to normalized device coordinates (NDC).

Use this helper for coordinates measured from the top-left of a viewport. The returned NDC coordinate uses the viewport center as (0, 0), X from -1 on the left to 1 on the right, and Y increasing upward. The conversion is xNdc = 2 * x / width - 1 and yNdc = 1 - 2 * y / height.

width and height default to the browser viewport’s innerWidth and innerHeight. The helper does not mutate its inputs and returns a new Vector2. Use ndcToPx for the inverse conversion.

Examples

const center = pxToNdc(400, 300, 800, 600)
// center.x === 0 and center.y === 0

Parameters

NameDescriptionDefault
x

Pixel-space X coordinate, measured from the left edge.

—
y

Pixel-space Y coordinate, measured from the top edge.

—
width?

Viewport width used for the conversion.

innerWidth
height?

Viewport height used for the conversion.

innerHeight

Returns

NDC coordinate equivalent to the pixel coordinate, with Y up.