使用 requestAnimationFrame 控制动画速度



我正在尝试为一个从左到右在画布上移动的正方形制作动画。我正在使用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 坐标。advanceSquare(s)s增加 1。但是,当我advanceSquare(s)更改为:

function advanceSquare(s) {
return s + 0.1;
}

速度保持不变。

你能提出一种减慢广场速度的方法吗?

谢谢!

requestAnimationFrame

以帧速率运行,即60fps。因此,您的代码每秒递增s60 次。我敢打赌,广场正在快速发展。您可以添加一个全局变量和增量,然后使用模来减慢每秒增量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);
}

我发现了我的代码的问题,并且有 2 个问题。

首先,requestAnimationFrame的回调方法传递一个参数,即DOMHighResTimeStamp,它指示当前时间(基于自时间起的毫秒数)。这意味着我们不能将s传递到main()。因此,代码应该是:

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

第二个问题是renderSquare(s)没有从advanceSquare(s)中获取s的更新值。为了做到这一点,我必须写:

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

最新更新