If you're seeing this message, it means we're having trouble loading external resources on our website.

# 旋转 3D 图形

### 学习三角函数的理由

$\begin{array}{rl}& {x}^{\prime }=x×\mathrm{cos}\left(\theta \right)\\ & {y}^{\prime }=x×\mathrm{sin}\left(\theta \right)\end{array}$

### 将一点绕原点旋转

$\begin{array}{rl}& x=r×\mathrm{cos}\left(\alpha \right)\\ & y=r×\mathrm{sin}\left(\alpha \right)\end{array}$

$\begin{array}{rl}& {x}^{\prime }=r×\mathrm{cos}\left(\alpha +\beta \right)\\ & {y}^{\prime }=r×\mathrm{sin}\left(\alpha +\beta \right)\end{array}$

$\begin{array}{rl}& {x}^{\prime }=r×\mathrm{cos}\left(\alpha \right)\mathrm{cos}\left(\beta \right)-r×\mathrm{sin}\left(\alpha \right)\mathrm{sin}\left(\beta \right)\\ & {y}^{\prime }=r×\mathrm{sin}\left(\alpha \right)\mathrm{cos}\left(\beta \right)+r×\mathrm{cos}\left(\alpha \right)\mathrm{sin}\left(\beta \right)\end{array}$

$\begin{array}{rl}& {x}^{\prime }=x×\mathrm{cos}\left(\beta \right)-y×\mathrm{sin}\left(\beta \right)\\ & {y}^{\prime }=y×\mathrm{cos}\left(\beta \right)+x×\mathrm{sin}\left(\beta \right)\end{array}$

### 写一个旋转的函数

var rotateZ3D = function(theta) {
var sinTheta = sin(theta);
var cosTheta = cos(theta);
for (var n = 0; n < nodes.length; n++) {
var node = nodes[n];
var x = node[0];
var y = node[1];
node[0] = x * cosTheta - y * sinTheta;
node[1] = y * cosTheta + x * sinTheta;
}
};

rotateZ3D(60);

### 在三个维度上旋转

var rotateX3D = function(theta) {
var sinTheta = sin(theta);
var cosTheta = cos(theta);
for (var n = 0; n < nodes.length; n++) {
var node = nodes[n];
var y = node[1];
var z = node[2];
node[1] = y * cosTheta - z * sinTheta;
node[2] = z * cosTheta + y * sinTheta;
}
};

var rotateY3D = function(theta) {
var sinTheta = sin(theta);
var cosTheta = cos(theta);
for (var n = 0; n < nodes.length; n++) {
var node = nodes[n];
var x = node[0];
var z = node[2];
node[0] = x * cosTheta + z * sinTheta;
node[2] = z * cosTheta - x * sinTheta;
}
};

rotateX3D(60);
rotateY3D(60);

### 用户交互

mouseDragged = function() {
rotateY3D(mouseX - pmouseX);
rotateX3D(mouseY - pmouseY);
};
mouseXmouseY 都是包含鼠标当前位置的内建变量。pmouseXpmouseY 是包含上一帧中鼠标位置的内建变量。 因此当 x 坐标增加的时候 (向右移动鼠标)，我们会将一个正值传递到 rotateY3D() 中并围绕 y 轴逆时针旋转立方体。