1 | function easeInOutSin(time) {
|
2 | return (1 + Math.sin(Math.PI * time - Math.PI / 2)) / 2;
|
3 | }
|
4 | export default function animate(property, element, to, options = {}, cb = () => {}) {
|
5 | const {
|
6 | ease = easeInOutSin,
|
7 | duration = 300
|
8 | } = options;
|
9 | let start = null;
|
10 | const from = element[property];
|
11 | let cancelled = false;
|
12 | const cancel = () => {
|
13 | cancelled = true;
|
14 | };
|
15 | const step = timestamp => {
|
16 | if (cancelled) {
|
17 | cb(new Error('Animation cancelled'));
|
18 | return;
|
19 | }
|
20 | if (start === null) {
|
21 | start = timestamp;
|
22 | }
|
23 | const time = Math.min(1, (timestamp - start) / duration);
|
24 | element[property] = ease(time) * (to - from) + from;
|
25 | if (time >= 1) {
|
26 | requestAnimationFrame(() => {
|
27 | cb(null);
|
28 | });
|
29 | return;
|
30 | }
|
31 | requestAnimationFrame(step);
|
32 | };
|
33 | if (from === to) {
|
34 | cb(new Error('Element already at target position'));
|
35 | return cancel;
|
36 | }
|
37 | requestAnimationFrame(step);
|
38 | return cancel;
|
39 | } |
\ | No newline at end of file |