js实现流星划过

实现流星划过效果的方法
使用HTML和CSS创建基础结构
<div class="meteor"></div>
.meteor {
position: absolute;
width: 2px;
height: 2px;
background: white;
border-radius: 50%;
box-shadow: 0 0 10px 3px white;
}
使用JavaScript生成动画
function createMeteor() {
const meteor = document.createElement('div');
meteor.className = 'meteor';
// 随机起始位置(屏幕顶部)
const startX = Math.random() * window.innerWidth;
meteor.style.left = `${startX}px`;
meteor.style.top = '0px';
document.body.appendChild(meteor);
// 随机动画时长(1-3秒)
const duration = 1000 + Math.random() * 2000;
// 随机终点位置(屏幕底部)
const endX = startX + (Math.random() * 200 - 100);
const endY = window.innerHeight;
// 动画效果
const animation = meteor.animate([
{ transform: `translate(0, 0)` },
{ transform: `translate(${endX - startX}px, ${endY}px)` }
], {
duration: duration,
easing: 'linear'
});
// 动画结束后移除元素
animation.onfinish = () => meteor.remove();
}
定时生成流星
// 每0.5-2秒生成一颗流星
setInterval(createMeteor, 500 + Math.random() * 1500);
// 初始生成几颗流星
for(let i = 0; i < 3; i++) {
setTimeout(createMeteor, Math.random() * 1000);
}
增强视觉效果
body {
background: #000;
overflow: hidden;
height: 100vh;
margin: 0;
}
.meteor::after {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 1px;
background: linear-gradient(90deg, white, transparent);
transform-origin: left center;
}
优化性能
// 限制最大流星数量
let meteorCount = 0;
const MAX_METEORS = 10;
function createMeteor() {
if(meteorCount >= MAX_METEORS) return;
meteorCount++;
// ...之前的创建代码...
animation.onfinish = () => {
meteor.remove();
meteorCount--;
};
}
添加拖尾效果
// 在createMeteor函数中添加
meteor.animate([
{ opacity: 1, width: '2px', height: '2px' },
{ opacity: 0.5, width: '4px', height: '4px' },
{ opacity: 0, width: '1px', height: '1px' }
], {
duration: duration,
easing: 'cubic-bezier(0.4, 0, 0.2, 1)'
});
这段代码会创建一个流星划过夜空的动画效果,流星会随机从屏幕顶部出现,以不同角度和速度划过屏幕,并在到达底部后消失。可以通过调整CSS和JavaScript参数来改变流星的外观和行为。






