从不同位置开始 CSS 动画

Starting a CSS animation from a different position

我正在构建一个太阳系模型,我正在使用 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 和我的完整代码。

您可以使用否定 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