-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcube.html
More file actions
71 lines (61 loc) · 2.17 KB
/
Copy pathcube.html
File metadata and controls
71 lines (61 loc) · 2.17 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
<!DOCTYPE html>
<head>
<title>Trying to create a rotating 3D cube</title>
</head>
<body>
<canvas id="a" width = "512" height="512"></canvas>
<script>
const ctx = document.getElementById("a").getContext("2d");
let frame = 0; //Frame number
let v1 = [0, -1];
let v2 = [1, 0];
let v3 = [0, 1];
let v4 = [-1, 0];
let v5 = [0, 0];
let v6 = [0, 0];
let v7 = [0, 0];
let v8 = [0, 0];
let s = 0;
let c = 0;
function convertToCanvasCoords(x, y){
//Convert coordinates from a coordinate system with the origin at the center (the canvas stretches from -2 to 2), to the coordinates used by the canvas (0 to 511)
let width = document.getElementById("a").width;
let height = document.getElementById("a").height;
return [256 + x * width/4, 256 + y * height/4];
}
function drawPixel(x, y){
//Draws a black pixel at (x, y).
//Here x and y are in a coordinate system with the origin at the center of the canvas.
ctx.fillStyle = "rgb(0, 0, 0)";
let centered = convertToCentered(x, y);
ctx.fillRect(centered[0], centered[1], 1, 1);
}
function drawLine(x1, y1, x2, y2, thickness){
//Draws a line from (x1, y1) to (x2, y2) of the specified thickness.
//Here x1, x2, y1, y2, and thickness are in a coordinate system with the origin at the center of the canvas.
let coords1 = convertToCanvasCoords(x1, y1);
let coords2 = convertToCanvasCoords(x2, y2);
ctx.strokeStyle = "rgb(0, 0, 0)";
ctx.lineWidth = thickness * document.getElementById("a").width;
ctx.beginPath();
ctx.moveTo(coords1[0], coords1[1]);
ctx.lineTo(coords2[0], coords2[1]);
ctx.stroke();
}
function drawFrame(){
ctx.reset();
s = Math.sin(frame / 40);
c = Math.cos(frame / 40);
v1 = [-c, -c];
v2 = [c, -c];
v3 = [-c, c];
v4 = [c, c];
drawLine(v1[0], v1[1], v2[0], v2[1], 0.02);
drawLine(v2[0], v2[1], v3[0], v3[1], 0.02);
drawLine(v3[0], v3[1], v4[0], v4[1], 0.02);
drawLine(v4[0], v4[1], v1[0], v1[1], 0.02);
frame++;
}
setInterval(drawFrame, 200);
</script>
</body>