在屏幕上移动一个正方形并移出另一侧

Moving a square across the screen and out the other side

我需要在屏幕上移动一个正方形。当它到达终点时,它应该会再次出现在连续循环的起点。

我可以使用 setInterval 来做到这一点。但我想使用 requestAnimationFrame 调用该函数。目前,正方形继续朝一个方向移动并离开屏幕。我的代码使用 jquery。

  let block = document.getElementById('mydiv');
  let startPos = 0;
  function moveStone(timestamp){
    startPos += 5;
    block.style.left = startPos + 'px';
    requestAnimationFrame(moveStone);
  }`enter code here`
  requestAnimationFrame(moveStone);

我希望正方形重新出现在起点处,但它正朝着一个方向继续前进。

代码中的循环可以通过多种方式实现。这是模数方法(警告!未经测试!);

  let block = document.getElementById('mydiv');
  let startPos = 0;
  const maxPos = 100;
  function moveStone(timestamp){
    startPos += 5;
    block.style.left = (startPos % maxPos) + 'px';
    requestAnimationFrame(moveStone);
  }
  requestAnimationFrame(moveStone);