Skip to content

Commit bf4447c

Browse files
committed
fix: correct animation frame rate calculation
1 parent 04ac9cb commit bf4447c

File tree

1 file changed

+29
-31
lines changed

1 file changed

+29
-31
lines changed

src/utils/create-animation.js

Lines changed: 29 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,41 @@
1-
const STEP60 = 1000 / 60; // 60fps
2-
const STEP1 = 1000 / 1; // 1fps
3-
4-
export default function createAnimation(fn) {
5-
let id;
6-
let time = 0;
7-
let lastTime = 0;
8-
let lastStep = 0;
1+
export default function createAnimationFrame(fn, fps = 60) {
2+
let id = null;
93
let paused = false;
10-
function loop(stamp) {
11-
if (!time) time = stamp;
12-
fn(time);
13-
let step = (stamp - lastTime);
14-
if (step < STEP60) step = STEP60;
15-
if (step > STEP1) step = lastStep || STEP1;
16-
if (lastTime) time += step;
17-
lastStep = step;
18-
lastTime = stamp;
4+
let duration = 1000 / fps;
5+
let time = 0;
6+
let last = 0;
7+
8+
function loop(now) {
9+
if (!time) {
10+
time = now;
11+
}
12+
let delta = now - last;
13+
if (last) {
14+
time += delta;
15+
}
16+
if (delta >= duration) {
17+
fn(time);
18+
last = now;
19+
}
1920
id = requestAnimationFrame(loop);
2021
}
22+
2123
id = requestAnimationFrame(loop);
24+
2225
return {
23-
resume() {
24-
if (id && paused) {
25-
paused = false;
26-
id = requestAnimationFrame(loop);
27-
}
28-
},
2926
pause() {
30-
if (id) {
31-
cancelAnimationFrame(id);
27+
if (!paused && id) {
3228
paused = true;
33-
}
34-
},
35-
cancel() {
36-
if (id) {
37-
paused = false;
3829
cancelAnimationFrame(id);
3930
id = null;
31+
last = 0;
4032
}
4133
},
42-
}
34+
resume() {
35+
if (paused) {
36+
paused = false;
37+
id = requestAnimationFrame(loop);
38+
}
39+
}
40+
};
4341
}

0 commit comments

Comments
 (0)