使用 GIF 移动蚂蚁边界

Marching ant border using a GIF

我知道有一种方法可以用线性渐变来做行进的蚂蚁,但它会吃掉大量 CPU(每个蚂蚁大约 10%)。我正在尝试制作替代解决方案,但发现 border-image-slice 令人困惑。

这是我正在使用的过时教程:http://www.chrisdanford.com/blog/2014/04/28/marching-ants-animated-selection-rectangle-in-css/

我删除了过时的 css 但我不确定如何切割图像以便蚂蚁在行进。图说:

We’ll start with a 10px x 10px animated gif that is composed of nine tiles: 1×1 in the corners, 1×8 or 8×1 on the edges, and 8×8 in the center.

body {
  background-color: green;
}

.box {
  width: 200px;
  height: 200px;
  background-color: black;
}

.marching {
  border: 1px solid transparent;
  border-image-source: url('https://i.imgsafe.org/e5bc19b03a.gif');
  border-image-slice: 1;
  border-image-repeat: stretch stretch;
}
<div class="box marching"></div>

谢谢

背景应该重复,而不是拉伸。这是你想要的吗?

body {
  background-color: green;
}

.box {
  width: 200px;
  height: 200px;
  background-color: black;
}

.marching {
  border: 1px solid transparent;
  border-image-source: url('https://i.imgsafe.org/e5bc19b03a.gif');
  border-image-slice: 1;
  border-image-repeat: repeat repeat;
}
<div class="box marching"></div>

您有什么理由不使用 canvas?

Canvas元素有一个lineDashOffset属性,常用于行进蚂蚁效果:
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset

如果您打算使用 GIF,看起来好像缩放不是您担心的事情,所以 canvas 可能是更好的方法。 Buffer-canvases 也可用于提高性能。

这是我找到的 CSS 版本,就 CPU 用法而言,它与其他版本相比如何?

body { background: green; }
.box {
  position: relative;
  width: 90px;
  height: 90px;
  overflow: hidden;
  margin: 10px;
  background: black;
}
.box * {
  position: absolute;
}
.box div {
  width: 100%;
  height: 100%;
}
.box div:nth-child(1) { transform: rotate(   0deg ); }
.box div:nth-child(2) { transform: rotate(  90deg ); }
.box div:nth-child(3) { transform: rotate( 180deg ); }
.box div:nth-child(4) { transform: rotate( 270deg ); }
.box i {
  left: 0;
  top: 0;
  width: 200%;
  border-bottom: 1px dashed white;
}
.box i {
  animation: marching 4s infinite linear;
}
@keyframes marching {
  from { transform: translateX( -50% ); }
  to   { transform: translateX(   0% ); }
}
<div class="box">
  <div><i></i></div>
  <div><i></i></div>
  <div><i></i></div>
  <div><i></i></div>
</div>

来源:https://jsfiddle.net/desandro/zm7Et/