learning-note icon indicating copy to clipboard operation
learning-note copied to clipboard

css 实现蚂蚁行军的特效

Open jackPanyj opened this issue 9 years ago • 0 comments

先来一张效果图

图是静态的,真正的效果应该是动态的。

先上代码:

html 部分:

<div class="ant">蚂蚁行军</div>

css 部分:

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.ant {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 50px;
  color: #00f;
  height: 300px;
  width: 300px;
  background-image: linear-gradient(#fff, #fff), repeating-linear-gradient(-45deg, currentColor 0, currentColor 10px, transparent 0, transparent 20px);
  background-clip: padding-box, border-box;
  border: 1px solid transparent;
  background-origin: border-box;
  animation: ant 12s infinite linear;
  background-size: 30px 30px;
}

@keyframes ant {
  to {
    background-position: 100% 100%;
  }
}

代码解释:

  1. 首先声明一点 background-image 如果存在多个图片的话, 其表现是前面的覆盖后面的。
  2. linear-gradient(#fff, #fff)做出白色的背景图作为第一个background-image
  3. repeating-linear-gradient(-45deg, currentColor 0, currentColor 10px, transparent 0, transparent 20px) 做出一个字体色与透明色间隔图案,作为第二个背景图
  4. 利用background-clip分别剪切俩个背景图, 第一个为padding-box, 第二个为 border-box
  5. 设置border1px, 背景色为透明色,这样就得到了一个静态的1px的边框
  6. 设置background-size 为合适的尺寸
  7. 制作动画帧, 然background-position慢慢移动到100%
  8. 应用动画,设置合适的时间间隔

demo链接

jackPanyj avatar Jun 30 '16 08:06 jackPanyj