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
| <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>星空动画</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="starry-sky"></canvas>
<script>
const canvas = document.getElementById('starry-sky');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const numStars = 150;
const stars = [];
class Star {
constructor() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.size = (Math.random() * 3 + 1) * .4;
const colors = [
'#fff',
'#f0f',
// '#0ff',
'#ff0'
];
this.color = colors[Math.floor(Math.random() * colors.length)];
this.speedX = (Math.random() * .5 + 1) / 3
this.speedY = (Math.random() * .5 + 1) / 3
console.log(this.speedX, this.speedY)
}
move() {
this.x += this.speedX;
this.y -= this.speedY;
if (this.x > canvas.width) {
this.x = 0;
}
if (this.y < 0) {
this.y = canvas.height;
}
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
}
}
function createStars() {
for (let i = 0; i < numStars; i++) {
stars.push(new Star());
}
}
function drawBackground() {
const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
gradient.addColorStop(0, '#000000');
gradient.addColorStop(.25, 'rgb(21,18,27)');
gradient.addColorStop(.5, 'rgba(32,28,42,1)');
gradient.addColorStop(1, 'rgb(44,52,99)');
// gradient.addColorStop(1, '#445299');
// gradient.addColorStop(1, '#1a1a4d');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBackground();
stars.forEach(star => {
star.move();
star.draw();
});
requestAnimationFrame(animate);
}
createStars();
animate();
// window.addEventListener('resize', () => {
// canvas.width = window.innerWidth;
// canvas.height = window.innerHeight;
// });
</script>
</body>
</html>
|