以下是一个简化的HTML和JavaScript代码示例,用于创建一个流星落到地面的动画效果。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>流星动画</title>
<style>
canvas {
background: #000;
display: block;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const W = canvas.width = window.innerWidth;
const H = canvas.height = window.innerHeight;
const halfW = W * 0.5;
const halfH = H * 0.5;
class Star {
constructor() {
this.x = Math.random() * W;
this.y = Math.random() * H;
this.coords = this.calculateCoords(this.x, this.y);
this.velocity = {
x: (Math.random() - 0.5) * 5,
y: (Math.random() - 0.5) * 5
};
this.angle = Math.atan2(this.velocity.y, this.velocity.x);
this.speed = 2;
this.size = Math.random() * 2;
this.brightness = Math.random() * 255;
}
update() {
this.x += this.velocity.x * this.speed;
this.y += this.velocity.y * this.speed;
if(this.x > W || this.x < 0) this.velocity.x *= -1;
if(this.y > H || this.y < 0) this.velocity.y *= -1;
}
draw() {
ctx.beginPath();
ctx.fillStyle = `hsl(25, 100%, ${this.brightness}%)`;
ctx.arc(...this.coords, this.size, 0, Math.PI * 2);
ctx.fill();
}
calculateCoords(x, y) {
const angle = Math.atan2(halfH - y, halfW - x);
const r = Math.hypot(halfW - x, halfH - y);
return [
halfW + r * Math.cos(angle),
halfH + r * Math.sin(angle)
];
}
}
const starfield = [];
const starCount = 1000;
for (let i = 0; i < starCount; i++) {
starfield.push(new Star());
}
function animate() {
ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
ctx.fillRect(0, 0, W, H);
starfield.forEach((star, index) => {
star.update();
star.draw();
});
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
这段代码创建了一个流星类,其中包含流星的属性,如位置、速度、颜色和大小。calculateCoords
函数将2D平面上的坐标转换为3D空间中的坐标。update
方法更新流星的位置,如果它超出了屏幕边界,就反弹。draw
方法在画布上绘制流星。主循环中创建了一个流星数组,并在animate
函数中更新和绘制它们。