js实现流星
实现流星效果的JavaScript代码
使用HTML5 Canvas和JavaScript可以轻松实现流星效果。以下是一个简单的实现方法:
// 获取Canvas元素和上下文
const canvas = document.getElementById('meteorCanvas');
const ctx = canvas.getContext('2d');
// 设置Canvas大小为窗口大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 流星对象
class Meteor {
constructor() {
this.reset();
}
reset() {
this.x = Math.random() * canvas.width;
this.y = -20;
this.speed = 2 + Math.random() * 5;
this.size = 1 + Math.random() * 3;
this.length = 5 + Math.random() * 15;
this.angle = Math.random() * Math.PI / 4;
}
update() {
this.x += Math.sin(this.angle) * this.speed;
this.y += Math.cos(this.angle) * this.speed;
if (this.y > canvas.height || this.x > canvas.width || this.x < 0) {
this.reset();
}
}
draw() {
ctx.beginPath();
ctx.moveTo(this.x, this.y);
ctx.lineTo(
this.x - Math.sin(this.angle) * this.length,
this.y - Math.cos(this.angle) * this.length
);
ctx.lineWidth = this.size;
ctx.strokeStyle = 'rgba(255, 255, 255, 0.7)';
ctx.stroke();
}
}
// 创建多个流星
const meteors = [];
for (let i = 0; i < 10; i++) {
meteors.push(new Meteor());
}
// 动画循环
function animate() {
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
meteors.forEach(meteor => {
meteor.update();
meteor.draw();
});
requestAnimationFrame(animate);
}
animate();
// 窗口大小改变时重置Canvas大小
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
HTML部分
需要在HTML中添加Canvas元素:
<!DOCTYPE html>
<html>
<head>
<title>流星效果</title>
<style>
body { margin: 0; overflow: hidden; background: #000; }
canvas { display: block; }
</style>
</head>
<body>
<canvas id="meteorCanvas"></canvas>
<script src="meteor.js"></script>
</body>
</html>
实现要点
- 使用Canvas绘制流星,性能优于DOM操作
- 每个流星有随机的位置、大小、速度和角度
- 流星飞出屏幕后会重置位置
- 动画循环使用requestAnimationFrame实现流畅动画
- 添加了淡出效果使流星尾部逐渐消失
自定义选项
可以修改以下参数调整效果:
- 流星数量:修改
meteors数组的初始长度 - 流星速度:调整
this.speed的随机范围 - 流星大小:修改
this.size的随机范围 - 流星长度:调整
this.length的随机范围 - 流星颜色:修改
ctx.strokeStyle的值
性能优化建议
对于大量流星的场景:

- 使用对象池技术重用流星对象
- 考虑使用WebGL实现更高效的渲染
- 降低动画帧率以节省CPU资源






