<div id="ball" style="width: 20px; height: 20px; background-color: blue; border-radius: 50%; position: absolute;"></div>
<button id="replayButton" style="position: absolute; top: 0;">Replay</button>
var ball = document.getElementById("ball");
var replayButton = document.getElementById("replayButton");
var requestId = null; // 用于存储requestAnimationFrame的ID
var gravity = 0.1; // 重力加速度
var dx = 2; // 初始水平速度
var dy = 0; // 初始垂直速度
var x = 100; // 初始水平位置
var y = 100; // 初始垂直位置
var bounceFactor = 0.7; // 弹性系数
var friction = 0.99; // 摩擦系数
function updateBallPosition() {
dy += gravity;
x += dx;
y += dy;
if (y >= window.innerHeight - ball.offsetHeight) {
y = window.innerHeight - ball.offsetHeight;
dy *= -bounceFactor;
}
if (x <= 0 || x >= window.innerWidth - ball.offsetWidth) {
dx *= -friction;
}
dx *= friction;
ball.style.left = x + 'px';
ball.style.top = y + 'px';
requestId = requestAnimationFrame(updateBallPosition);
}
function resetAnimation() {
if (requestId) {
cancelAnimationFrame(requestId); // 取消当前动画帧
}
// 重置位置和速度
x = 100;
y = 100;
dx = 2;
dy = 0;
// 重新开始动画
requestId = requestAnimationFrame(updateBallPosition);
}
// 为重播按钮添加点击事件监听器
replayButton.addEventListener('click', resetAnimation);
// 初始启动动画
requestAnimationFrame(updateBallPosition);
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.