If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

# 生成 3D 图形

### 定义长方体

``````// 创建一个立方体，其其中一个顶点在位置 (x, y, z)
// 长度为 d，宽度为 w，高度为 h。
var createCuboid = function(x, y, z, w, h, d) {
var nodes = [];
var edges = [];
var shape = { 'nodes': nodes, 'edges': edges };
return shape;
};``````

``````var shape = createCuboid(0, 0, 0, 100, 160, 50);
var node0 = shape.nodes[0];``````

``````var createCuboid = function(x, y, z, w, h, d) {
var nodes = [[x, y, z ], [x, y, z+d], [x, y+h, z ], [x, y+h, z+d], [x+w, y, z ], [x+w, y, z+d], [x+w, y+h, z ], [x+w, y+h, z+d]];

var edges = [[0, 1], [1, 3], [3, 2], [2, 0], [4, 5], [5, 7], [7, 6], [6, 4], [0, 4], [1, 5], [2, 6], [3, 7]];

return { 'nodes': nodes, 'edges': edges};
};``````

``var shape = createCuboid(0, 0, 0, 100, 160, 50);``

``var nodes = shape.nodes; var edges = shape.edges;``

### 使用多个形状

``````var shape1 = createCuboid(-120, -20, -20, 240, 40, 40);
var shape2 = createCuboid(-120, -50, -30, -20, 100, 60);
var shape3 = createCuboid( 120, -50, -30, 20, 100, 60);
var shapes = [shape1, shape2, shape3];``````

``````// 绘制边
stroke(edgeColor);
for (var shapeNum = 0; shapeNum < shapes.length; shapeNum++) {
var nodes = shapes[shapeNum].nodes;
var edges = shapes[shapeNum].edges;
for (var e = 0; e < edges.length; e++) {
var n0 = edges[e][0];
var n1 = edges[e][1];
var node0 = nodes[n0];
var node1 = nodes[n1];
line(node0[0], node0[1], node1[0], node1[1]);
}
}``````

``````// 绘制点
fill(nodeColor);
noStroke();
for (var shapeNum = 0; shapeNum < shapes.length; shapeNum++) {
var nodes = shapes[shapeNum].nodes;
for (var n = 0; n < nodes.length; n++) {
var node = nodes[n]; ellipse(node[0], node[1], nodeSize, nodeSize);
}
}``````

``var rotateZ3D = function(theta, nodes) { ... };``

``````mouseDragged = function() {
var dx = mouseX - pmouseX;
var dy = mouseY - pmouseY;
for (var shapeNum = 0; shapeNum < shapes.length; shapeNum++) {
var nodes = shapes[shapeNum].nodes;
rotateY3D(dx, nodes);
rotateX3D(dy, nodes);
}
};``````