js实现星星闪烁的效果
使用CSS动画实现星星闪烁
通过CSS的@keyframes和animation属性可以轻松实现星星闪烁效果。定义一个透明度变化的动画,并将其应用到星星元素上。
.star {
width: 20px;
height: 20px;
background-color: gold;
border-radius: 50%;
animation: twinkle 1s infinite alternate;
}
@keyframes twinkle {
from { opacity: 0.3; }
to { opacity: 1; }
}
使用JavaScript动态控制闪烁
通过setInterval或requestAnimationFrame动态修改星星的样式属性,实现更灵活的闪烁效果。

const star = document.querySelector('.star');
let opacity = 0.3;
let increasing = true;
function animateStar() {
if (increasing) {
opacity += 0.05;
if (opacity >= 1) increasing = false;
} else {
opacity -= 0.05;
if (opacity <= 0.3) increasing = true;
}
star.style.opacity = opacity;
requestAnimationFrame(animateStar);
}
animateStar();
创建多个随机闪烁的星星
在页面上生成多个星星,并为每个星星设置不同的闪烁频率和延迟。

const container = document.getElementById('stars-container');
const starCount = 20;
for (let i = 0; i < starCount; i++) {
const star = document.createElement('div');
star.className = 'star';
star.style.left = `${Math.random() * 100}%`;
star.style.top = `${Math.random() * 100}%`;
star.style.animationDuration = `${0.5 + Math.random() * 1.5}s`;
star.style.animationDelay = `${Math.random() * 2}s`;
container.appendChild(star);
}
使用Canvas绘制闪烁星星
通过Canvas API绘制更复杂的星星形状,并实现闪烁效果。
const canvas = document.getElementById('star-canvas');
const ctx = canvas.getContext('2d');
let brightness = 0.3;
let increasing = true;
function drawStar(x, y, size, brightness) {
ctx.save();
ctx.translate(x, y);
ctx.beginPath();
for (let i = 0; i < 5; i++) {
ctx.lineTo(0, size);
ctx.translate(0, size);
ctx.rotate((Math.PI * 2) / 10);
ctx.lineTo(0, -size * 0.5);
ctx.translate(0, -size * 0.5);
ctx.rotate((Math.PI * 2) / 10);
}
ctx.fillStyle = `rgba(255, 215, 0, ${brightness})`;
ctx.fill();
ctx.restore();
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (increasing) {
brightness += 0.01;
if (brightness >= 1) increasing = false;
} else {
brightness -= 0.01;
if (brightness <= 0.3) increasing = true;
}
drawStar(100, 100, 15, brightness);
requestAnimationFrame(animate);
}
animate();
使用GSAP库实现高级动画
GreenSock Animation Platform (GSAP) 提供了更强大的动画控制能力。
const stars = document.querySelectorAll('.star');
stars.forEach(star => {
gsap.to(star, {
opacity: 0.3,
duration: 1 + Math.random(),
repeat: -1,
yoyo: true,
ease: "power1.inOut"
});
});
以上方法提供了从简单到复杂的多种实现方式,可以根据项目需求选择最适合的方案。CSS动画适合简单场景,JavaScript控制提供更多灵活性,Canvas适合自定义图形,而GSAP则适合复杂的动画序列。






