-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
92 lines (77 loc) · 2.11 KB
/
script.js
File metadata and controls
92 lines (77 loc) · 2.11 KB
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
82
83
84
85
86
87
88
89
90
91
92
const canvas = document.getElementById("cubeCanvas");
const ctx = canvas.getContext("2d");
const width = canvas.width;
const height = canvas.height;
// Cube dimensions
const cubeSize = 100;
// Define cube vertices (8 points)
let vertices = [
[-1, -1, -1],
[ 1, -1, -1],
[ 1, 1, -1],
[-1, 1, -1],
[-1, -1, 1],
[ 1, -1, 1],
[ 1, 1, 1],
[-1, 1, 1]
].map(v => v.map(coord => coord * cubeSize));
// Define cube edges
const edges = [
[0,1],[1,2],[2,3],[3,0], // back face
[4,5],[5,6],[6,7],[7,4], // front face
[0,4],[1,5],[2,6],[3,7] // connections
];
// Rotation angles
let angleX = 0;
let angleY = 0;
// Projection function
function project([x,y,z]) {
// Shift cube forward so z is always positive
const zOffset = 600;
const scale = 400 / (z + zOffset);
const px = x * scale + width/2;
const py = y * scale + height/2;
return [px, py];
}
// Rotation functions
function rotateX([x,y,z], angle) {
const cos = Math.cos(angle);
const sin = Math.sin(angle);
return [x, y*cos - z*sin, y*sin + z*cos];
}
function rotateY([x,y,z], angle) {
const cos = Math.cos(angle);
const sin = Math.sin(angle);
return [x*cos - z*sin, y, x*sin + z*cos];
}
function drawCube() {
ctx.clearRect(0,0,width,height);
let transformed = vertices.map(v => {
let rotatedX = rotateX(v, angleX);
let rotatedXY = rotateY(rotatedX, angleY);
return project(rotatedXY);
});
ctx.strokeStyle = "#0ff";
ctx.lineWidth = 2;
edges.forEach(([a,b]) => {
const [x1,y1] = transformed[a];
const [x2,y2] = transformed[b];
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.stroke();
});
}
// Delta time animation
let lastTime = 0;
function animate(timestamp) {
if (!lastTime) lastTime = timestamp;
const deltaTime = (timestamp - lastTime) / 1000; // seconds
lastTime = timestamp;
const speed = parseFloat(document.getElementById("speed").value);
angleX += speed * deltaTime;
angleY += speed * deltaTime;
drawCube();
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);