js实现流星划过
实现流星划过效果
使用JavaScript和CSS可以创建一个简单的流星划过动画效果。以下是实现方法:
HTML结构
<div class="meteor"></div>
CSS样式
.meteor {
position: absolute;
width: 100px;
height: 2px;
background: linear-gradient(to right, rgba(255,255,255,0), #fff);
transform: rotate(-45deg);
transform-origin: left;
animation: meteor 3s linear infinite;
opacity: 0;
}
@keyframes meteor {
0% {
transform: rotate(-45deg) translateX(0);
opacity: 1;
}
70% {
opacity: 1;
}
100% {
transform: rotate(-45deg) translateX(-1000px);
opacity: 0;
}
}
JavaScript动态生成流星
function createMeteor() {
const meteor = document.createElement('div');
meteor.className = 'meteor';
// 随机位置
const startX = Math.random() * window.innerWidth;
const startY = Math.random() * window.innerHeight / 2;
meteor.style.left = `${startX}px`;
meteor.style.top = `${startY}px`;
// 随机大小和速度
const size = Math.random() * 100 + 50;
const duration = Math.random() * 3 + 2;
meteor.style.width = `${size}px`;
meteor.style.animationDuration = `${duration}s`;
document.body.appendChild(meteor);
// 动画结束后移除元素
meteor.addEventListener('animationend', () => {
meteor.remove();
});
}
// 每隔一段时间创建新流星
setInterval(createMeteor, 800);
增强效果的方法
添加拖尾效果 修改CSS中的背景渐变:
background: linear-gradient(
to right,
rgba(255,255,255,0),
#fff,
rgba(255,255,255,0.7),
rgba(255,255,255,0)
);
随机颜色 在JavaScript中添加:
const colors = ['#fff', '#9cf', '#f9f', '#fc9'];
const randomColor = colors[Math.floor(Math.random() * colors.length)];
meteor.style.background = `linear-gradient(to right, rgba(255,255,255,0), ${randomColor})`;
多流星同时出现 调整创建间隔和数量:
function createMultipleMeteors() {
const count = Math.floor(Math.random() * 3) + 1;
for(let i = 0; i < count; i++) {
setTimeout(createMeteor, i * 300);
}
}
setInterval(createMultipleMeteors, 1000);
性能优化
使用requestAnimationFrame替代setInterval可以获得更流畅的动画效果:

function meteorLoop(timestamp) {
if(!lastTime || timestamp - lastTime > 800) {
createMeteor();
lastTime = timestamp;
}
requestAnimationFrame(meteorLoop);
}
let lastTime;
requestAnimationFrame(meteorLoop);
通过调整CSS属性和JavaScript参数,可以创建出各种不同风格的流星效果,包括大小、速度、颜色和轨迹的变化。






