HTML流星雨
HTML本身不支持流星雨的效果,这通常需要结合JavaScript和CSS来实现。以下是一个简单的实现示例:
<!DOCTYPE html>
<html>
<head>
<style>
body, html {
margin: 0;
padding: 0;
height: 100%;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="starry-sky"></canvas>
<script>
function StarrySky(canvasId) {
this.canvas = document.getElementById(canvasId);
this.ctx = this.canvas.getContext('2d');
this.width = window.innerWidth;
this.height = window.innerHeight;
this.stars = [];
this.init = function() {
this.canvas.width = this.width;
this.canvas.height = this.height;
this.populateStars();
this.animate();
};
this.populateStars = function() {
for (var i = 0; i < this.width * this.height / 1000; i++) {
var star = new Star(this.ctx, this.width, this.height);
this.stars.push(star);
}
};
this.animate = function() {
requestAnimationFrame(this.animate.bind(this));
this.ctx.clearRect(0, 0, this.width, this.height);
for (var i = 0; i < this.stars.length; i++) {
this.stars[i].draw();
}
};
}
function Star(ctx, width, height) {
this.ctx = ctx;
this.x = Math.random() * width;
this.y = Math.random() * height;
this.radius = Math.random() * 2;
this.speed = Math.random() * 0.05;
this.draw = function() {
this.y += this.speed;
this.ctx.beginPath();
this.ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
this.ctx.fillStyle = 'white';
this.ctx.fill();
if (this.y > height) {
this.y = 0;
}
};
}
window.onload = function() {
var sky = new StarrySky('starry-sky');
sky.init();
};
</script>
</body>
</html>
这段代码定义了StarrySky
类,它初始化画布,生成一些随机的“星”对象,并在画布上不断重绘它们。每个星星都有随机的位置、半径和下落速度,形成流星雨的效果。每当一个星星移出画布,它就会被重置到顶部。这个简单的示例提供了流星雨背景的基本概念,你可以根据需要进一步扩展和定制。
评论已关闭