
本文详解如何基于纯 javascript 四元数(quaternion)驱动 html/css 3d 立方体,实现高精度、无万向节锁的鼠标拖拽旋转,并集成物理感十足的惯性衰减动画。
本文详解如何基于纯 javascript 四元数(quaternion)驱动 html/css 3d 立方体,实现高精度、无万向节锁的鼠标拖拽旋转,并集成物理感十足的惯性衰减动画。
在 Web 前端中,使用 CSS transform: rotate3d() 直接操控 3D 变换虽简洁,但叠加多次欧拉角旋转极易引发万向节锁(Gimbal Lock),导致失控或翻转异常。而四元数作为三维空间旋转的数学最优表示,天然规避该问题,且支持平滑插值与复合旋转。本文将完整呈现一个生产级实现:从鼠标输入映射到轴-角旋转,到四元数乘法累积姿态,再到基于物理模型的惯性滚动(velocity + exponential friction)。
核心原理:四元数如何表达旋转?
四元数 q = (x, y, z, w) 可由单位旋转轴 v = (vx, vy, vz) 和旋转角度 θ 构造:
q = (vx·sin(θ/2), vy·sin(θ/2), vz·sin(θ/2), cos(θ/2))。
关键点在于:CSS 的 rotate3d(x, y, z, α) 中的 α 是弧度制总旋转角,而非 w 值——必须通过 α = 2·arccos(w) 还原,否则旋转幅度严重失真。原代码中 apply() 方法直接用 w 作角度,是核心错误。
完整可运行实现(精简注释版)
<style>
.scene { perspective: 15em; height: 100vh; display: flex; align-items: center; justify-content: center; }
.cube { width: 5em; height: 5em; position: relative; transform: translateZ(-2.5em); transform-style: preserve-3d; }
.face { position: absolute; width: 5em; height: 5em; display: flex; align-items: center; justify-content: center; }
.front { transform: rotateY(0deg) translateZ(2.5em); background: cyan; }
.top { transform: rotateX(90deg) translateZ(2.5em); background: lime; }
.back { transform: rotateY(180deg) translateZ(2.5em); background: yellow; }
.bottom { transform: rotateX(-90deg) translateZ(2.5em); background: blue; }
.right { transform: rotateY(90deg) translateZ(2.5em); background: white; }
.left { transform: rotateY(-90deg) translateZ(2.5em); background: magenta; }
</style><div class="scene">
<div class="cube">
<div class="face front">front</div>
<div class="face top">top</div>
<div class="face back">back</div>
<div class="face bottom">bottom</div>
<div class="face right">right</div>
<div class="face left">left</div>
</div>
</div>
<script>
"use strict";
class Vec3 {
constructor(x, y, z) { this.x = x; this.y = y; this.z = z; }
length() { return Math.sqrt(this.x**2 + this.y**2 + this.z**2); }
normalize() { const l = this.length(); if (l) { this.x /= l; this.y /= l; this.z /= l; } return this; }
scale(k) { this.x *= k; this.y *= k; this.z *= k; return this; }
static sub(a, b) { return new Vec3(a.x-b.x, a.y-b.y, a.z-b.z); }
}
class Quat {
constructor(x, y, z, w) { this.x = x; this.y = y; this.z = z; this.w = w; }
// 由轴-角构造:axis 必须为单位向量,angle 为弧度
static fromAxisAngle(axis, angle) {
const half = angle / 2;
const s = Math.sin(half);
return new Quat(axis.x * s, axis.y * s, axis.z * s, Math.cos(half));
}
// 四元数乘法:q * r(注意顺序!)
static mul(q, r) {
return new Quat(
q.w*r.x + q.x*r.w + q.y*r.z - q.z*r.y,
q.w*r.y - q.x*r.z + q.y*r.w + q.z*r.x,
q.w*r.z + q.x*r.y - q.y*r.x + q.z*r.w,
q.w*r.w - q.x*r.x - q.y*r.y - q.z*r.z
);
}
}
// 全局状态管理
const cube = document.querySelector('.cube');
let orientation = new Quat(0, 0, 0, 1); // 初始单位四元数
let velocity = new Vec3(0, 0, 0);
const friction = 3; // 衰减系数,越大停止越快
let impulse = new Vec3(0, 0, 0); // 本帧累积的瞬时角动量
let isDragging = false;
let lastMouse = null;
// 应用四元数到 DOM
function applyQuat(q) {
const angle = 2 * Math.acos(Math.max(-1, Math.min(1, q.w))); // 防止浮点误差溢出
const sinHalf = Math.sin(angle / 2);
const axis = sinHalf > 1e-6
? new Vec3(q.x / sinHalf, q.y / sinHalf, q.z / sinHalf)
: new Vec3(1, 0, 0); // 无旋转时默认绕 X 轴(实际不影响)
cube.style.transform = `translateZ(-2.5em) rotate3d(${axis.x}, ${axis.y}, ${axis.z}, ${angle}rad)`;
}
// 鼠标/触摸事件处理
['mousedown', 'touchstart'].forEach(type => {
document.addEventListener(type, e => {
e.preventDefault();
isDragging = true;
velocity = new Vec3(0, 0, 0);
impulse = new Vec3(0, 0, 0);
const pos = type === 'touchstart'
? e.touches[0]
: e;
lastMouse = new Vec3(pos.clientX, pos.clientY, 0);
});
});
['mouseup', 'touchend'].forEach(type => {
document.addEventListener(type, () => isDragging = false);
});
['mousemove', 'touchmove'].forEach(type => {
document.addEventListener(type, e => {
if (!isDragging) return;
e.preventDefault();
const pos = type === 'touchmove'
? e.touches[0]
: e;
const current = new Vec3(pos.clientX, pos.clientY, 0);
const delta = Vec3.sub(current, lastMouse);
// 将屏幕位移映射为旋转轴:横向拖拽 → 绕 Y 轴,纵向 → 绕 X 轴
// 组合成一个斜轴,更符合直觉(如右下拖拽产生 Z 轴分量)
const axis = new Vec3(-delta.y, delta.x, 0).normalize();
const angle = delta.length() * 0.01; // sensitivity
impulse = Vec3.sub(impulse, axis.scale(angle)); // 累积角冲量(注意符号)
lastMouse = current;
});
});
// 主循环:整合拖拽冲量 + 惯性衰减
function animate(timestamp) {
const deltaSec = (timestamp - (animate.last || timestamp)) / 1000;
animate.last = timestamp;
if (isDragging && impulse.length() > 0.001) {
// 将冲量转换为瞬时角速度(避免帧率依赖)
velocity = impulse.scale(1 / Math.max(deltaSec, 0.001));
impulse = new Vec3(0, 0, 0);
} else if (!isDragging && velocity.length() > 0.0001) {
// 指数衰减:ω(t) = ω₀·e^(-friction·t)
const decay = Math.exp(-deltaSec * friction);
velocity.scale(decay);
// 生成本次衰减对应的旋转增量
const angle = velocity.length() * deltaSec;
if (angle > 0) {
const axis = velocity.normalize();
const dq = Quat.fromAxisAngle(axis, angle);
orientation = Quat.mul(dq, orientation);
}
}
applyQuat(orientation);
requestAnimationFrame(animate);
}
animate.last = 0;
requestAnimationFrame(animate);
</script>
关键注意事项与优化点
- 角度还原必须严谨:Math.acos(q.w) 的输入必须钳位在 [-1, 1],否则 NaN 会导致旋转中断;
- 旋转轴方向一致性:鼠标水平移动应主要引起绕 Y 轴旋转(rotate3d(0,1,0,α)),垂直移动绕 X 轴(rotate3d(1,0,0,α))。示例中通过 (-dy, dx, 0) 构造轴,符合右手定则;
- 性能敏感操作:避免在 mousemove 中频繁调用 getBoundingClientRect() 或触发重排;所有计算均基于 clientX/Y,零开销;
- 触摸兼容性:统一处理 touchstart/touchmove/touchend,并正确提取 touches[0] 坐标;
- 惯性物理合理性:采用指数衰减 e^(-friction·t) 比线性衰减更符合真实阻尼效果,且 friction=3 在 60fps 下约 0.5 秒内衰减至 20% 初始速度。
此方案完全脱离第三方库,仅依赖原生 API,兼具教学价值与工程可用性。掌握四元数旋转后,你可进一步拓展至陀螺仪控制、多物体协同旋转或 WebGL 场景集成。
把任意文章或文档内容转换成精美的全屏翻页 HTML 演示文件(幻灯片风格)。当用户发来一篇文章、文档链接、Markdown 内容、或粘贴的文本,并且希望生成演示用的 HTML 时触发。支持任意内容来源:iWiki 链接、KM 链接、本地文件路径、直接粘贴的文本。生成的 HTML 文件保存到本地工作区,并通过企微直接发送给用户。触发词示例:帮我把这篇文章做成PPT、转成演示文档、生成HTML幻灯片、做个演示、转成可以演示的格式、article to deck、make a slide。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










