跳至主要內容

流体加载动画

望间代码HTML&CSS加载动画动画大约 2 分钟

流体加载动画

使用 SVG 制作的流体加载动画

效果展示

<div class="conatiner">
  <div class="loading">
    <span style="--i:1"></span>
    <span style="--i:2"></span>
    <span style="--i:3"></span>
    <span style="--i:4"></span>
    <span style="--i:5"></span>
    <span style="--i:6"></span>
    <span style="--i:7"></span>
  </div>

  <svg>
    <filter id="gooey">
      <feGaussianBlur in="SourceGraphic" stdDeviation="10" />
      <!-- feColorMatrix 用于彩色滤光片转换 -->
      <feColorMatrix
        values="
                1 0 0 0 0
                0 1 0 0 0
                0 0 1 0 0
                0 0 0 20 -10
      "
      />
    </filter>
  </svg>
</div>
.conatiner {
  width: 100%;
  height: 250px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.conatiner svg {
  width: 0;
  height: 0;
}

.conatiner .loading {
  width: 200px;
  height: 200px;
  position: relative;
  filter: url(#gooey);
}

.conatiner .loading span {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: block;
  animation: loading 4s ease-in-out infinite;
  /* var函数用来插入css变量的值,css变量名称以--开头 */
  animation-delay: calc(0.2s * var(--i));
}

.conatiner .loading span::before {
  content: "";
  position: absolute;
  top: 0;
  left: calc(50% - 20px);
  width: 40px;
  height: 40px;
  background: linear-gradient(#fce4ec, #03a9f4);
  border-radius: 50%;
  box-shadow: 0 0 30px #03a9f4;
}

@keyframes loading {
  0% {
    transform: rotate(0deg);
  }

  50%,
  100% {
    transform: rotate(360deg);
  }
}

实现思路

  • 第一步首先我们要让元素能够旋转起来,使用 transform 中的 rotate 进行 2D 的 360° 旋转
  • 第二步我们可以通过 CSS 变量(--开头的形式)结合 animation-delay 来控制每个元素的动画从何时开始
  • 最后为了让整个旋转的元素能够呈现流体形,我们需要使用 filter 滤镜来特殊处理一下

代码解释

filter元素 id 属性作为滤镜的唯一标识 feGaussianBlur 定义模糊效果, in="SourceGraphic" 这个部分定义了由整个图像创建效果, stdDeviation 属性定义模糊量

这里涉及到一些复杂的颜色处理,直接上 svgfeColorMatrix,这也是过滤的一种类型,使用矩阵来影响颜色的通道

矩阵计算 RGBA 自已每行的最终值,每个 RGBA 通道有自身的 RGBA 通道,最后一个值是一个乘数,最后 RGBA 的值从上向下

/* R G B A 1 */
   1 0 0 0 0 // R = 1*R + 0*G + 0*B + 0*A + 0
   0 1 0 0 0 // G = 0*R + 1*G + 0*B + 0*A + 0
   0 0 1 0 0 // B = 0*R + 0*G + 1*B + 0*A + 0
   0 0 0 1 0 // A = 0*R + 0*G + 0*B + 1*A + 0

参考

CSS 液体加载动画open in new window

上次编辑于:
贡献者: ViewRoom