使用CSS3实现一个随机粒子动画效果

386 阅读1分钟

"CSS3实现随机粒子动画效果

@keyframes particles {
   0% { 
      transform: translate(0, 0);
      opacity: 1;
   }
   100% { 
      transform: translate(calc(100vw * 1.5), calc(100vh * 1.5));
      opacity: 0;
   }
}

.particle {
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
   width: 10px;
   height: 10px;
   background-color: #fff;
   border-radius: 50%;
   animation: particles 2s linear infinite;
}

body {
   overflow: hidden;
}
<!DOCTYPE html>
<html>
<head>
   <title>Random Particle Animation</title>
   <link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\">
</head>
<body>
   <script>
      const numParticles = 50;
      const container = document.querySelector('body');

      for (let i = 0; i < numParticles; i++) {
         const particle = document.createElement('div');
         particle.classList.add('particle');
         particle.style.animationDelay = `${Math.random() * 2}s`;
         container.appendChild(particle);
      }
   </script>
</body>
</html>

以上是使用CSS3实现随机粒子动画效果的代码。首先,我们定义了一个名为particles的关键帧动画,它包含了从初始位置到最终位置的变化。在起始帧,粒子的位置是初始位置,透明度是1;在结束帧,粒子的位置是偏移了视窗宽度和高度的1.5倍的位置,透明度是0。这个关键帧动画会在2秒钟内线性无限循环播放。

然后,在HTML中,我们创建了一个包含粒子的容器。通过JavaScript,我们动态地创建了一定数量的粒子元素,并将其附加到容器中。每个粒子都具有particle类,这样它们就可以应用关键帧动画。我们还为每个粒子设置了不同的动画延迟,以实现随机的效果。

最后,我们在CSS中设置了body元素的overflow属性为hidden,以防止粒子溢出页面。

通过以上代码,我们可以实现一个具有随机粒子动画效果的页面。每个粒子都会以不同的速度和方向移动,最终淡出消失。这种动画效果可以为网站添加一些视觉吸引力,并为用户提供更好的体验。

注意:为了使代码能正常运行,请将CSS代码保存为styles.css文件,并将其与HTML文件放在同一目录中。"