Celestial Programming : Rotation Around an Arbitrary Axis

This creates a rotation matrix, which rotates a vector about any arbitrary axis. The axis is specified as a unit vector v\vec v. For example [1,0,0] rotates about the x axis, norm([1,1,0]) rotates about an axis 45° to the x,y axes.

R(v,θ)=[vx2(1cosθ)+cosθvxvy(1cosθ)vzsinθvxvz(1cosθ)+vysinθvxvy(1cosθ)+vzsinθvy2(1cosθ)+cosθvyvz(1cosθ)vxsinθvxvz(1cosθ)vysinθvyvz(1cosθ)+vxsinθvz2(1cosθ)+cosθ] R(\vec{v}, \theta)= \begin{bmatrix} v_x^2(1-\cos \theta) + \cos \theta & v_x v_y (1-\cos \theta) - v_z \sin \theta & v_x v_z (1-\cos \theta) + v_y \sin \theta \\ v_x v_y(1-\cos \theta) + v_z \sin \theta & v_y^2 (1-\cos \theta) + \cos \theta & v_y v_z (1-\cos \theta) - v_x \sin \theta \\ v_x v_z(1-\cos \theta) - v_y \sin \theta & v_y v_z (1-\cos \theta) + v_x \sin \theta & v_z^2 (1-\cos \theta) + \cos \theta \\ \end{bmatrix}



//Greg Miller (gmiller@gregmiller.net) 2025
//https://www.celestialprogramming.com/
//Released as public domain

//Rotation around arbitrary axis, v=[x,y,z] θ=angle in radians
function rotateAroundAxis(v,θ){
    const v_x=v[0];
    const v_y=v[1];
    const v_z=v[2];
    const cosθ=Math.cos(θ);
    const sinθ=Math.sin(θ);
    
    const r=[
        [v_x*v_x*(1-cosθ) + cosθ     , v_x*v_y*(1-cosθ) - v_z*sinθ , v_x*v_z*(1-cosθ) + v_y*sinθ ],
        [v_x*v_y*(1-cosθ) + v_z*sinθ , v_y*v_y*(1-cosθ) + cosθ     , v_y*v_z*(1-cosθ) - v_x*sinθ ],
        [v_x*v_z*(1-cosθ) - v_y*sinθ , v_y*v_z*(1-cosθ) + v_x*sinθ , v_z*v_z*(1-cosθ) + cosθ     ]
    ];

    return r;
}