快速实现一个加载菊花组件

734 阅读1分钟

QQ20210723-112217.gif

原理

画了12个指针,然后12个指针颜色透明度依次暗淡,30°角度旋转排列,然后设置CSS动画,每次循环用时0.8秒,无限循环次数,每次循环采用步进式每次12步,线性进行,代码如下:

// SpinnerLoading.tsx
import React from "react";
import style from './index.module.scss'

const SpinnerLoading = () => {
  return (
    <span className={style.spinner}>
      {
        new Array(12).fill(Math.random()).map((v, index) => (
          <i key={v} style={{
            transform: `rotate(${30 * (index + 1)}deg)`,
            opacity: 1 - (index / 16),
          }}></i>
        ))
      }
    </span>
  )
}

export default SpinnerLoading

// index.module.scss
.spinner {
  position: relative;
  display: inline-block;
  width: 30px;
  max-width: 100%;
  height: 30px;
  max-height: 100%;
  vertical-align: middle;
  animation: infinite circle 800ms  linear;
  animation-timing-function: steps(12);
  i {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    &::after {
      display: block;
      width: 2px;
      height: 25%;
      margin: 0 auto;
      background-color: currentColor;
      border-radius: 40%;
      content: ' ';
    }
  }
}
@keyframes circle {
  from {
    transform: rotate(0);
  }
  to {
    transform: rotate(360deg);
  }
}