以下是一个简单的HTML和JavaScript代码示例,用于创建流星雨效果。你可以将这段代码保存为HTML文件,并通过浏览器打开查看效果。
<!DOCTYPE html>
<html>
<head>
<title>流星雨</title>
<style>
body, html {
margin: 0;
padding: 0;
height: 100%;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const W = window.innerWidth;
const H = window.innerHeight;
canvas.width = W;
canvas.height = H;
let particles = [];
let particleCount = 200;
function init() {
for (let i = 0; i < particleCount; i++) {
particles.push(new Particle());
}
animate();
}
function animate() {
ctx.clearRect(0, 0, W, H);
for (let i = 0; i < particleCount; i++) {
let p = particles[i];
p.draw();
p.update();
}
requestAnimationFrame(animate);
}
function Particle() {
this.x = Math.random() * W;
this.y = Math.random() * H;
this.vx = -.5 + Math.random();
this.vy = -.5 + Math.random();
this.size = Math.random() * 2;
this.life = 1;
this.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = 'white';
ctx.fill();
}
this.update = function() {
this.x += this.vx * 5;
this.y += this.vy * 5;
if (this.x > W || this.x < 0) this.vx *= -1;
if (this.y > H || this.y < 0) this.vy *= -1;
}
}
init();
</script>
</body>
</html>
这段代码会在页面上创建一个canvas
元素,并用JavaScript实现流星雨的效果。你可以根据需要调整particleCount
来改变雨中星星的数量,以及通过调整颜色和大小来自定义样式。