-
Notifications
You must be signed in to change notification settings - Fork 12
/
starfield.php
114 lines (85 loc) · 3.77 KB
/
starfield.php
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<!--
CC3.0 Distribution License
NOTE: This software is released under CC3.0 creative commons
If using in own projects please give credit to the original author,
By linking to:
http://www.webgltutorials.org
Thanks :-)
//--><html>
<head>
<title>Starfield Demo</title>
</head>
<body>
<canvas id = "canvas" width = "800" height = "500"></canvas>
<script>
var ScreenWidth = 800;
var ScreenHeight = 500;
var MAX_DEPTH = 10;
class Star {
constructor() {
this.reset = function()
{
this.x = 1 - Math.random() * 2.0;
this.y = 1 - Math.random() * 2.0;
this.z = Math.random() * -MAX_DEPTH;
this.x2d = 0;
this.y2d = 0;
this.angle = 0.001;
}
this.project = function()
{
// Rotate this star around the Z axis using trigonometry (sine & cosine)
this.x = this.x * Math.cos(this.angle) - this.y * Math.sin(this.angle);
this.y = this.y * Math.cos(this.angle) + this.x * Math.sin(this.angle);
// Calculate "Camera View" -- Project the 3D star coordinates to the 2D screen
this.x2d = (ScreenHeight/ScreenWidth) * ScreenWidth * this.x / this.z + (ScreenWidth / 2);
this.y2d = ScreenHeight * this.y / this.z + (ScreenHeight / 2);
// this.x2d = ScreenWidth * this.x / this.z + (ScreenWidth / 2);
this.y2d = ScreenHeight * this.y / this.z + (ScreenHeight / 2);
// Move star toward the camera
this.z += 0.0025;
// Reset this star if it goes outside of the viewing area
if (this.x2d <= 0 || this.x2d >= ScreenWidth ||
this.y2d <= 0 || this.y2d >= ScreenHeight)
this.reset();
}
this.draw = function()
{
var star_size = 3 - (-this.z / 2);
var star_color = (MAX_DEPTH + this.z) / (MAX_DEPTH*2);
window.gfx.globalAlpha = star_color;
window.gfx.fillStyle = 'white';
window.gfx.fillRect(this.x2d, this.y2d, star_size, star_size);
window.gfx.globalAlpha = 1;
}
// Reset (initialize) on object construction
this.reset();
}
}
// Initialize stars
var STARS_MAX = 2000;
var stars = new Array(STARS_MAX);
for (let i = 0; i < STARS_MAX; i++)
stars[i] = new Star();
// Create and initialize canvas
var canvas = document.getElementById("canvas");
var context = window.gfx = canvas.getContext('2d');
// Main animation loop
setInterval(function() {
// Clear screen
gfx.beginPath();
gfx.fillStyle = 'black';
gfx.rect(0, 0, 800, 500);
gfx.fill();
// Move and draw stars
gfx.beginPath();
gfx.fillStyle = 'white';
for (let i = 0; i < STARS_MAX; i++) {
stars[i].project();
stars[i].draw();
}
gfx.fill();
}, 0);
</script>
</body>
</html>