在我的城市交通模型的持续构建中,我正在努力把握好时机。
我希望能够
a) 设置动画速度——我认为它现在正在尝试 60fps,但我希望能够设置得更快或更慢。我试过这个代码:
var fps = 5;
function draw() {
setTimeout(function() {
requestAnimationFrame(animate);
}, 1000 / fps);
}
draw();
Run Code Online (Sandbox Code Playgroud)
但鉴于 rAF 被称为三个不同的时间,我不确定如何实现它。这三个我都试过了,没有成功。
b) 我想在每个“车辆”的发射上设置一个轻微的延迟,这样它们就不会同时发射。
在这里小提琴:https : //jsfiddle.net/g3yhr00L/
要限制动画,只需执行以下操作:
// define some FRAME_PERIOD in units of ms - may be floating point
// if you want uSecond resolution
function animate(time) {
// return if the desired time hasn't elapsed
if ( (time - lastTime) < FRAME_PERIOD) {
requestAnimationFrame(animate);
return;
}
lastTime = time;
// animation code
}
Run Code Online (Sandbox Code Playgroud)
要更改车辆的开始时间,您需要在车辆本身的逻辑中构建它。我不会单独为每辆车制作动画。
这是我在寻求限制 FPS 时发现的一种方法。
这真的很好,并且带有说明:编辑:无需使用 Date.now()。
var fps = 30;
var now;
var then;
var interval = 1000/fps;
var delta;
function draw(now) {
if (!then) { then = now; }
requestAnimationFrame(draw);
delta = now - then;
if (delta > interval) {
// update time stuffs
// Just `then = now` is not enough.
// Lets say we set fps at 10 which means
// each frame must take 100ms
// Now frame executes in 16ms (60fps) so
// the loop iterates 7 times (16*7 = 112ms) until
// delta > interval === true
// Eventually this lowers down the FPS as
// 112*10 = 1120ms (NOT 1000ms).
// So we have to get rid of that extra 12ms
// by subtracting delta (112) % interval (100).
// Hope that makes sense.
then = now - (delta % interval);
// ... Code for Drawing the Frame ...
}
}
draw();
Run Code Online (Sandbox Code Playgroud)
您可以在这里找到原始文章:http : //codetheory.in/controlling-the-frame-rate-with-requestanimationframe/