如何为滚动矩形制作动画

How to animate a rolling rectangle

我想设置一个矩形动画,使其从屏幕左侧滚动到屏幕右侧。请注意,变换原点不应位于矩形的中心,而应位于右下角,这样它就不会越过 "hr" 线或以任何方式反弹。

这是我到目前为止所取得的成就,但我希望它不断移动直到到达屏幕的右边缘:

hr {
  margin: 0;
}

div {
  width: 135px;
  height: 135px;
  box-shadow: inset 0 0 10px #000000;
  transform-origin: right bottom;
  animation-name: move;
  animation-duration: 2s;
  animation-timing-function: linear;
  animation-delay: 0;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

@keyframes move {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(90deg);
  }
}
<div></div>
<hr>

有趣的是,我会考虑添加一个翻译,技巧是在两种状态之间快速切换以便能够继续移动。

您正在以 90 度 旋转您的元素,如果我们只考虑最终状态,这样两种情况之间的快速切换将不可见,因此您可以再次旋转元素并重复相同的技巧,直到到达所需位置。

hr {
  margin: 0;
}

div {
  width: 135px;
  height: 135px;
  box-shadow: inset 0 0 10px #000000;
  transform-origin: right bottom;
  animation-name: move;
  animation-duration: 4s;
  animation-timing-function: linear;
  animation-delay: 0;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

@keyframes move {
  0% {
    transform: rotate(0deg);
  }
  25% {
    transform: rotate(90deg);
  }
  25.01% {
    transform: translateX(calc(1 * 135px)) rotate(0deg);
  }
  50% {
    transform: translateX(calc(1 * 135px)) rotate(90deg);
  }
  50.01% {
    transform: translateX(calc(2 * 135px)) rotate(0deg);
  }
  75% {
    transform: translateX(calc(2 * 135px)) rotate(90deg);
  }
  75.01% {
    transform: translateX(calc(3 * 135px)) rotate(0deg);
  }
  100% {
    transform: translateX(calc(3 * 135px)) rotate(90deg);
  }
}
<div></div>
<hr>

您需要随时更改变换原点:

hr {
  margin: 0;
}

div {
  width: 135px;
  height: 135px;
  box-shadow: inset 0 0 10px #000000;
  transform-origin: right bottom;
  animation-name: move;
  animation-duration: 12s;
  animation-timing-function: linear;
  animation-delay: 0;
  animation-iteration-count: infinite;
  animation-direction: alternate;
  margin-top: 20px;
}

@keyframes move {
  0% {
    transform: rotate(0deg);
  transform-origin: right bottom;
  }
  25% {
    transform: rotate(90deg);
  transform-origin: right bottom;
  }
  25.1% {
    transform:   translate(100%, 100%) rotate(90deg);
    transform-origin: top right;
  }
  50% {
    transform:  translate(100%, 100%) rotate(180deg);
    transform-origin: top right;
  }
  50.1% {
    transform: translate(300%, 100%) rotate(180deg);
    transform-origin: left top;
  }
  75% {
    transform: translate(300%, 100%) rotate(270deg);
    transform-origin: left top;
  }
  75.1% {
    transform: translate(400%, 0%) rotate(270deg);
    transform-origin: left bottom;
  }
  100% {
    transform: translate(400%, 0%) rotate(360deg);
    transform-origin: left bottom;
  }
}
<div>TEST</div>
<hr>