How to Convert Degrees to Radians in Three.js
In Three.js, 3D rotations are calculated using radians rather than
degrees, which can be unintuitive for developers accustomed to standard
360-degree measurements. This article explains how the Three.js
MathUtils module simplifies this process by providing the
built-in helper functions degToRad and
radToDeg to perform seamless angle conversions in your 3D
applications.
Why Three.js Uses Radians
By default, the 3D graphics engine of Three.js uses radians for
rotation properties on objects like meshes, cameras, and lights (e.g.,
mesh.rotation.x). One full rotation of a circle is equal to
360 degrees, which is equivalent to \(2\pi\) radians (approximately 6.28318).
Because writing math equations using fractions of \(\pi\) can be difficult to read and
maintain, the MathUtils namespace provides utility
functions to bridge the gap between human-readable degrees and
machine-ready radians.
Converting Degrees to Radians with degToRad
The THREE.MathUtils.degToRad() method converts any
degree value into its equivalent radian value.
Syntax
THREE.MathUtils.degToRad( degrees );Code Example
Instead of manually calculating radians using the formula
degrees * (Math.PI / 180), you can pass your degree value
directly into the utility function:
import * as THREE from 'three';
// Create a basic mesh
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
// Rotate the cube 45 degrees around the Y-axis
cube.rotation.y = THREE.MathUtils.degToRad(45);Converting Radians to Degrees with radToDeg
If you are reading rotation data from a Three.js object and need to
display it in a user interface or output it to a log in degrees, you can
use the reverse function: THREE.MathUtils.radToDeg().
Syntax
THREE.MathUtils.radToDeg( radians );Code Example
// Get the current rotation of the cube in radians
const currentRadians = cube.rotation.y;
// Convert the radians back to degrees
const currentDegrees = THREE.MathUtils.radToDeg(currentRadians);
console.log(currentDegrees); // Outputs: 45Behind the Scenes
The mathematical equations running inside these
MathUtils helpers are highly optimized standard conversion
formulas:
- Degrees to Radians:
degrees * (Math.PI / 180) - Radians to Degrees:
radians * (180 / Math.PI)
Using the built-in MathUtils helpers keeps your code
clean, readable, and less prone to manual mathematical errors.