使用 Less 实现动态星空

76 阅读1分钟

效果

主要代码

.title {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-clip: text;
  -webkit-background-clip: text;
  font-size: 28px;
}

// 阴影生成函数
.function-getShadows(@n) {
  @shadows: ~`(function() {
      var shadows = [];
      for (var i = 0; i < @{n}; i++) {
        shadows.push(
          Math.round(Math.random() * 2000) + 'px ' + 
          Math.round(Math.random() * 2000) + 'px #fff'
        );
      }
      return shadows.join(',');
    })()`;
}

.random-size(@size) {
  width: ~"@{size}px";
  height: ~"@{size}px";
}

// 修复后的循环函数
.function-auto() {
  // 初始持续时间(改为合理值)
  @initial-duration: 400s;
  @count: 1000; // 生成星星数量
  
  .loop(@counter, @duration, @count) when (@counter < 6) {
    @random-size: @counter; // 使用计数器作为大小
    
    .layer@{counter} {
      position: fixed;
      .random-size(@random-size);
      border-radius: 50%;
      left: 0;
      top: 0; // 从底部开始
      
      // 生成当前层的阴影
      .function-getShadows(@count);
      box-shadow: @shadows;
      
      // 应用动画
      animation: moveUp @duration linear infinite;

      &::after {
        content: '';
        position: fixed;
        left: 0;
        top: 100vh;
        border-radius: inherit;
        width: inherit;
        height: inherit;
        box-shadow: inherit;
        // 伪元素也应用动画
        // animation: moveUp @duration linear infinite;
      }
    }
    
    // 递归调用,传递新的持续时间值
    .loop((@counter + 1), (@duration / 2), (@count / 2));
  }
  
  // 启动循环,从5开始,初始持续时间为20s
  .loop(1, @initial-duration, @count);
}

.function-auto();

// 修改动画关键帧
@keyframes moveUp {
  to {
    transform: translateY(-100vh); // 确保完全移出视口
  }
}