rendering
code
html
<div class="ball">🏀</div>
<button class="go">go</button>
Copy the code
css
:root{-top: 0px;
}
.ball {
position: absolute;
top: var(--top);
font-size: 100px;
}
.go {
position: fixed;
right: 80px;
top: 50px;
}
Copy the code
javascript
let prev = 0;
// Animation duration
const duration = 3000;
// The height of the ball from the ground
const height = 500;
function bounce(t) {
if(! prev) { prev = t; requestAnimationFrame(bounce);return;
}
// Calculate the animation runtime
let diff = t - prev;
// The x value corresponding to the current animation time
let x = diff / duration;
// The y value corresponding to the current animation time
let y = easeOutBounce(x);
// The height corresponding to the y value
let top = y * height;
document.documentElement.style.setProperty('--top', top + 'px');
if (diff >= duration) {
return;
}
requestAnimationFrame(bounce);
}
let go = document.querySelector(".go")
go.addEventListener('click'.(e) = > {
prev = 0;
requestAnimationFrame(bounce);
})
// Simulate the bounce effect of timing function
// Reference: https://easings.net/#easeOutBounce
function easeOutBounce(x) {
const n1 = 7.5625;
const d1 = 2.75;
if (x < 1 / d1) {
return n1 * x * x;
} else if (x < 2 / d1) {
return n1 * (x -= 1.5 / d1) * x + 0.75;
} else if (x < 2.5 / d1) {
return n1 * (x -= 2.25 / d1) * x + 0.9375;
} else {
return n1 * (x -= 2.625 / d1) * x + 0.984375; }}Copy the code
The online demo
Jsbin.com/labidan/edi…