Skip to main content

perspective: Perspective Projection Matrix

3D perspective transformation

The perspective projection creates a 4×4 transformation matrix that maps a 3D frustum to normalized device coordinates with depth perspective. Objects further from the camera appear smaller, creating realistic 3D depth perception:

f=1tan(fov/2)f = \frac{1}{\tan(\text{fov}/2)} nf=1nearfarn_f = \frac{1}{\text{near} - \text{far}} Mpersp=(faspect0000f0000(far+near)nf1002farnearnf0)M_{\text{persp}} = \begin{pmatrix} \frac{f}{\text{aspect}} & 0 & 0 & 0 \\ 0 & f & 0 & 0 \\ 0 & 0 & (\text{far} + \text{near}) \cdot n_f & -1 \\ 0 & 0 & 2 \cdot \text{far} \cdot \text{near} \cdot n_f & 0 \end{pmatrix}

The resulting coordinates require perspective division by the w-component to obtain final NDC.

Parameter Definitions

ParameterDescriptionRange
fovVertical field of view (radians)(0,π)(0, \pi)
aspectWidth/height aspect ratio(0,)(0, \infty)
nearNear clipping plane distance(0,far)(0, \text{far})
farFar clipping plane distance(near,)(\text{near}, \infty)
Live Editor
const fragment = () => {
      const fov = sin(iTime).mul(0.8).add(1.5)
      const proj = perspective(fov, 1, 0.1, 10)
      const coord = vec3(uv.sub(0.5).mul(2), 2)
      const transformed = proj.mul(vec4(coord, 1))
      const depth = transformed.w.div(10)
      const color = vec3(depth, abs(transformed.xy).mul(0.5))
      return vec4(color, 1)
}