<!DOCTYPE html>
<html>
<head>
<title>最美星空</title>
<style>
canvas {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
}
</style>
</head>
<body>
<canvas id="space"></canvas>
<script>
const canvas = document.getElementById('space');
const ctx = canvas.getContext('2d');
const WIDTH = canvas.width = window.innerWidth;
const HEIGHT = canvas.height = window.innerHeight;
const halfWidth = WIDTH / 2;
const halfHeight = HEIGHT / 2;
const stars = [];
const starCount = 2000;
function random(min, max) {
if (arguments.length < 2) {
max = min;
min = 0;
}
return min + (max - min) * Math.random();
}
function randomColor() {
return 'rgb(' + random(0, 255) + ',' + random(0, 255) + ',' + random(0, 255) + ')';
}
function Star(x, y) {
this.x = x;
this.y = y;
this.radius = random(0.5, 2);
this.speed = random(1, 2);
this.angle = random(0, 360);
this.color = randomColor();
}
Star.prototype.update = function() {
this.angle += this.speed;
};
Star.prototype.draw = function() {
ctx.save();
ctx.beginPath();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle * Math.PI / 180);
ctx.fillStyle = this.color;
ctx.arc(0, 0, this.radius, 0, 2 * Math.PI);
ctx.fill();
ctx.restore();
};
function createStars() {
for (let i = 0; i < starCount; i++) {
stars.push(new Star(random(WIDTH), random(HEIGHT)));
}
}
function animate() {
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
ctx.fillRect(0, 0, WIDTH, HEIGHT);
ctx.globalCompositeOperation = 'lighter';
stars.forEach((star) => {
star.update();
star.draw();
});
window.requestAnimationFrame(animate);
}
评论已关闭