-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
81 lines (60 loc) · 1.85 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const g = canvas.getContext('2d');
const nodes = [[-1, -1, -1], [-1, -1, 1], [-1, 1, -1], [-1, 1, 1],
[1, -1, -1], [1, -1, 1], [1, 1, -1], [1, 1, 1]];
const 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]];
let mouseX = 0, prevMouseX, mouseY = 0, prevMouseY;
canvas.addEventListener('mousemove', function (event) {
prevMouseX = mouseX;
prevMouseY = mouseY;
mouseX = event.x;
mouseY = event.y;
const incrX = (mouseX - prevMouseX) * 0.01;
const incrY = (mouseY - prevMouseY) * 0.01;
rotateCuboid(incrX, incrY);
drawCuboid();
});
function scale(factor0, factor1, factor2) {
nodes.forEach(function (node) {
node[0] *= factor0;
node[1] *= factor1;
node[2] *= factor2;
});
}
function rotateCuboid(angleX, angleY) {
const sinX = Math.sin(angleX);
const cosX = Math.cos(angleX);
const sinY = Math.sin(angleY);
const cosY = Math.cos(angleY);
nodes.forEach(function (node) {
const x = node[0];
const y = node[1];
let z = node[2];
node[0] = x * cosX - z * sinX;
node[2] = z * cosX + x * sinX;
z = node[2];
node[1] = y * cosY - z * sinY;
node[2] = z * cosY + y * sinY;
});
}
function drawCuboid() {
g.save();
g.clearRect(0, 0, canvas.width, canvas.height);
g.translate(canvas.width / 2, canvas.height / 2);
g.strokeStyle = '#000';
g.beginPath();
edges.forEach(function (edge) {
const p1 = nodes[edge[0]];
const p2 = nodes[edge[1]];
g.moveTo(p1[0], p1[1]);
g.lineTo(p2[0], p2[1]);
});
g.closePath();
g.stroke();
g.restore();
}
scale(80, 120, 160);
rotateCuboid(Math.PI / 5, Math.PI / 9);