CSS 精灵动画白色闪光反向

问题描述

我制作了一个仅使用 CSS 动画的简单精灵。

@keyframes swordAttack {
    0% {
        background-position: 0 0;
    }
    50% {
        background-position: -5305px 0;
    }
    100% {
        background-position: 0 0;
    }
}

我遇到的唯一问题是,当动画结束(并反向播放)时,会出现白色闪光,即缺少一帧。

不幸的是很难解释,但就像:

@@@@@@x@@@@@@

其中“x”看起来像是缺失的帧或白色闪光。这也是动画将反转并播放直到到达第一帧的点。这个丢帧/闪退很奇怪,因为我没有丢帧。

我的精灵宽度为 5305px,每个动画部分的宽度相等,存在于 17 个“帧”中。

我正在使用此代码运行动画:

animation: swordAttack 1s steps(17) normal;

一切都很完美,除了我可以称之为“白色闪光”。

希望有人能告诉我哪里出了问题。

enter image description here

解决方法

我认为动画中存在错误。看看你的动画应该从 0% 开始,然后是 50%,一直到 100%。但是在您的解决方案中,它的起点是 100% 然后 50% 一直到 100%,这可能是我认为的错误。 将 100% 更改为 0%,然后从 50% 一直到 100%

@keyframes swordAttack {
    0% {
        background-position: 0 0;
    }
    50% {
        background-position: -5305px 0;
    }
    100% {
        background-position: 0 0;
    }
}
,

像下面那样做:

.anim {
  width:100px;
  display:inline-flex;
  background-image:url(https://i.stack.imgur.com/NYtWt.png);
  background-size:auto 100%; /* make it full height and keep width auto */
  animation: swordAttack 1s steps(16) infinite alternate; /* replace infinite with 2 to get only one ruunning */
}

.anim::before {
  content:"";
  padding-top:80.6%; /* this is based on the ratio of one image,adjust it based on the sprite */
}

@keyframes swordAttack {
    100% {
        background-position: right; /* simply move to right */
    }
}
<div class="anim"></div>

<div class="anim" style="width:50px"></div>

由于 steps() 的工作方式,上述内容缺少一帧,但您可以按如下方式进行编辑以获取所有帧:

.anim {
  width:100px;
  display:inline-flex;
  background-image:url(https://i.stack.imgur.com/NYtWt.png);
  background-size:auto 100%; /* make it full height and keep width auto */
  animation: swordAttack 1s steps(17) infinite alternate; /* replace infinite with 2 to get only one ruunning */
}

.anim::before {
  content:"";
  padding-top:80.6%; /* this is based on the ratio of one image,adjust it based on the sprite */
}

@keyframes swordAttack {
    100% {
        background-position: calc(100% + 100%/16) 0; 
    }
}
<div class="anim"></div>

<div class="anim" style="width:50px"></div>