Javascript 使用requestAnimationFrame控制动画速度

Javascript 使用requestAnimationFrame控制动画速度,javascript,Javascript,我正在尝试设置一个正方形从左到右在画布上移动的动画。我正在使用requestAnimationFrame来实现这一点。不幸的是,我无法控制正方形的速度 我当前的代码如下所示: // Functions // =========================== // Square -> Square // start the world with initial state s, e.g main(0) function main(s) { requestAnimationFra

我正在尝试设置一个正方形从左到右在画布上移动的动画。我正在使用requestAnimationFrame来实现这一点。不幸的是,我无法控制正方形的速度

我当前的代码如下所示:

// Functions
// ===========================

// Square -> Square
// start the world with initial state s, e.g main(0)

function main(s) {
  requestAnimationFrame(main);
  advanceSquare(s);
  renderSquare(s);
}

// =========

// Square -> Square
// move square to the right

function advanceSquare(s) {
  s++;
}

// =========

// Square -> Image
// render the square on screen
// (check-expect)

function renderSquare(s) {
  renderScreen(screenWidth, screenHeight);
  ctx.fillStyle = squareColour;
  ctx.fillRect(s, squareYCoord, squareSides, squareSides);
}

// =========

// Number Number -> Image
// render the screen

function renderScreen(screenWidth, screenHeight) {
  ctx.fillStyle = screenColour;
  ctx.fillRect(0, 0, screenWidth, screenHeight);
}

s表示正方形的x坐标。advanceSquares将增加1。但是,当我将advanceSquares更改为:

速度保持不变

你能建议一种降低广场速度的方法吗

谢谢

requestAnimationFrame以帧速率运行,即60fps。所以你的代码每秒递增60次。我打赌那个广场移动得很快。您可以添加一个全局变量和增量,然后使用模来降低每秒s增量的次数

let counter = 0;

//change 20 to whatever speed you want
function advanceSquare(s) {
  if (counter % 20 == 0) s++;
}

//increment counter in the animation loop
function main(s) {
  counter++
  advanceSquare(s);
  renderSquare(s);
  requestAnimationFrame(main);
}

我发现我的代码有两个问题

首先,requestAnimationFrame的回调方法被传递给一个参数DOMHighResTimeStamp,该参数基于自时间原点起的毫秒数指示当前时间。这意味着我们不能将s传递到main。因此,守则应为:

function main() {
  requestAnimationFrame(main);
  advanceSquare(s);
  renderSquare(s);
}
第二个问题是renderSquares没有从advanceSquares获取s的更新值。为了做到这一点,我必须写:

function main() {
  requestAnimationFrame(main);
  renderSquare(advanceSquare(s));
}

下面是一个示例,我使用timestamp参数测量requestAnimationFrames之间的时间增量,并计算每指定的动态RPM每时间增量的齿轮旋转:。同样,在获得时间增量后,可以将其发送到advanceSquare函数,该函数指定每个时间段的新x坐标。不要假设requestAnimationFrame的速率稳定,更不要假设所有用户的速率都是唯一的。上一条注释有权使用增量时间移动对象。定义每个对象的速度,单位为px/秒,而不是px/帧。
function main() {
  requestAnimationFrame(main);
  renderSquare(advanceSquare(s));
}