【问题标题】:Starting a CSS animation from a different position从不同的位置开始 CSS 动画
【发布时间】:2021-11-07 05:08:30
【问题描述】:

我正在构建一个太阳系模型,我正在使用 CSS 动画来为围绕太阳移动的行星设置动画,如下所示:

.earthMini {
  border-radius: 50%;
  position: absolute;
  --radius: 1rem;
  top: calc(50% - var(--radius));
  left: calc(50% - var(--radius));
  width: calc(2 * var(--radius));
  height: calc(2 * var(--radius));
  background: url("../../planetTextures/earth.jpg") repeat-x;
  background-size: 100% 100%;
  animation: earthOrbit 45s linear infinite, translateBackground 50s infinite linear;
}
@keyframes earthOrbit {
  from {
    transform: rotate(0deg) translateX(13rem) rotate(0deg);
  }
  to {
    transform: rotate(360deg) translateX(13rem) rotate(-360deg);
  }
}

这很好用,但是当页面首次加载时,所有行星都从相同的起始位置开始动画:

我正在寻找一种方法,让每个行星在其轨道上都有不同的起始位置。

我有一个带有完整代码的codesandbox here

【问题讨论】:

    标签: javascript html css reactjs css-animations


    【解决方案1】:

    您可以使用否定的animation-delay 规则让动画在其初始动画中进一步开始。

    您可以通过 css 中的一些任意值进行设置,或使用 javascript 应用实际随机值。

    .earthMini {
      border-radius: 50%;
      position: absolute;
      --radius: 1rem;
      top: calc(50% - var(--radius));
      left: calc(50% - var(--radius));
      width: calc(2 * var(--radius));
      height: calc(2 * var(--radius));
      background: url("../../planetTextures/earth.jpg") repeat-x;
      background-size: 100% 100%;
      animation: earthOrbit 45s linear infinite, translateBackground 50s infinite linear;
      animation-delay: -45s; // <- this will place earth at the point of animation for 45s, 
    }
    @keyframes earthOrbit {
      from {
        transform: rotate(0deg) translateX(13rem) rotate(0deg);
      }
      to {
        transform: rotate(360deg) translateX(13rem) rotate(-360deg);
      }
    }
    

    your codepen with some modifications

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      相关资源
      最近更新 更多