Animation using Pure Javascript

To bounce we can use CSS property top and position:absolute for the ball inside the field with position:relative.

The bottom coordinate of the field is field.clientHeight. The CSS top property refers to the upper edge of the ball. So it should go from 0 till field.clientHeight - ball.clientHeight, that’s the final lowest position of the upper edge of the ball.

To to get the “bouncing” effect we can use the timing function bounce in easeOut mode.

Here’s the final code for the animation:

1
2
3
4
5
6
7
8
9
let to = field.clientHeight - ball.clientHeight;

animate({
duration: 2000,
timing: makeEaseOut(bounce),
draw(progress) {
ball.style.top = to * progress + 'px'
}
});

In the task info:task/animate-ball we had only one property to animate. Now we need one more: elem.style.left.

The horizontal coordinate changes by another law: it does not “bounce”, but gradually increases shifting the ball to the right.

We can write one more animate for it.

As the time function we could use linear, but something like makeEaseOut(quad) looks much better.

The code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let height = field.clientHeight - ball.clientHeight;
let width = 100;

// animate top (bouncing)
animate({
duration: 2000,
timing: makeEaseOut(bounce),
draw: function(progress) {
ball.style.top = height * progress + 'px'
}
});

// animate left (moving to the right)
animate({
duration: 2000,
timing: makeEaseOut(quad),
draw: function(progress) {
ball.style.left = width * progress + "px"
}
});