How to Convert Euler to Quaternion in Three.js

In Three.js, 3D rotations can be represented using either Euler angles (orientations along the X, Y, and Z axes) or Quaternions (four-dimensional numbers that avoid gimbal lock). This article provides a quick, practical guide on how to convert an Object3D’s rotation from Euler angles to a Quaternion representation, detailing both the automatic synchronization built into Three.js and manual conversion methods.

Understanding Euler and Quaternion in Object3D

Every Object3D in Three.js (such as meshes, cameras, and groups) contains both a .rotation property (which uses THREE.Euler) and a .quaternion property (which uses THREE.Quaternion).

By default, Three.js automatically synchronizes these two properties. If you change the Euler angles using object.rotation, Three.js automatically updates object.quaternion behind the scenes, and vice versa.

Method 1: Direct Access via Automatic Synchronization

Because of automatic synchronization, the easiest way to get the Quaternion representation of an object’s Euler rotation is simply to read its .quaternion property.

// Create a 3D object
const mesh = new THREE.Mesh(geometry, material);

// Set rotation using Euler angles (in radians)
mesh.rotation.set(Math.PI / 4, 0, Math.PI / 2);

// Access the corresponding Quaternion directly
const currentQuaternion = mesh.quaternion; 
console.log(currentQuaternion); // Outputs the updated Quaternion

Method 2: Manual Conversion Using setFromEuler

If you have a standalone THREE.Euler object that is not attached to an Object3D, or if you want to perform a manual conversion, you can use the setFromEuler() method of the THREE.Quaternion class.

// 1. Define your Euler angles (X, Y, Z in radians, and optional Euler order)
const euler = new THREE.Euler(Math.PI / 4, 0, Math.PI / 2, 'XYZ');

// 2. Instantiate a new Quaternion
const quaternion = new THREE.Quaternion();

// 3. Convert the Euler angles to the Quaternion
quaternion.setFromEuler(euler);

console.log(quaternion); // Outputs the converted Quaternion

Applying a Manual Quaternion to an Object3D

Once you have manually calculated or converted a Quaternion, you can apply it directly to your 3D object. When you update the quaternion, Three.js will automatically update the object’s .rotation Euler angles.

// Apply the converted quaternion to your object
myObject.quaternion.copy(quaternion);